Skip to content

Commit

Permalink
Add LoginCookieCleaner
Browse files Browse the repository at this point in the history
  • Loading branch information
joemaller committed Feb 24, 2024
1 parent 7ec528e commit 7e80d86
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ A common baseline of repeated functions, filters and actions used across our Wor
- **Admin Separators**
Admin Separators have been moved to their own library: [wp-admin-separators](https://github.com/ideasonpurpose/wp-admin-separators)

- **Remove Stale Login Cookies**
Repeatedly spinning up local dev environments often bloats **localhost** cookies with stale `wordpress_logged_in` entries. Once these accumulate, the local server will eventually fail with a bad request and the error message *"Your browser sent a request that this server could not understand. Size of a request header field exceeds server limit."* The cookie can be removed using the browser's dev tools, if the error is recognized -- but it often isn't. Instead, wp-theme-init removes stale login cookies from the `wp_login` hook, preventing the issue. This only runs on development environments when WP_DEBUG is set.

- **Media**
Several media related features will be enabled:

Expand Down
6 changes: 6 additions & 0 deletions src/ThemeInit.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@ public function __construct($options = [])
*/
new ThemeInit\Admin\LastLogin();


/**
* Clear stale wordpress_logged_in cookies
*/
New ThemeInit\Admin\LoginCookieCleaner();

/**
* Add Metabox Reset buttons to Admin User Profiles
*/
Expand Down
41 changes: 41 additions & 0 deletions src/ThemeInit/Admin/LoginCookieCleaner.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace IdeasOnPurpose\ThemeInit\Admin;

class LoginCookieCleaner
{
public $WP_DEBUG;

public function __construct()
{
// bridge WP_DEBUG for testing
$this->WP_DEBUG = defined('WP_DEBUG') && WP_DEBUG;

add_action('wp_login', [$this, 'remove']);
}

public function remove()
{
if (!$this->WP_DEBUG) {
return;
}

$stale_cookies = 0;
foreach ($_COOKIE as $key => $value) {
if (strpos($key, 'wordpress_logged_in') !== false) {
unset($_COOKIE[$key]);
setcookie($key, '', -1, '/');
$stale_cookies++;
}
}

if ($stale_cookies > 0) {
$msg = sprintf(
'IdeasOnPurpose\\wp-theme-init removed %d invalid `wordpress_logged_in` cookie%s',
$stale_cookies,
$stale_cookies == 1 ? '' : 's'
);
error_log($msg);
}
}
}

0 comments on commit 7e80d86

Please sign in to comment.