Skip to content

Instantly share code, notes, and snippets.

@clockworkgeek
Created March 12, 2015 11:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clockworkgeek/b123882d785378b43ea0 to your computer and use it in GitHub Desktop.
Save clockworkgeek/b123882d785378b43ea0 to your computer and use it in GitHub Desktop.
Purge excess sessions caused by increased `gc_maxlifetime` and https://github.com/clockworkgeek/Magento-Remember-Me
#!/usr/bin/env php
<?php
/**
* Place this script in your Magento root and optionally set the executable flag.
*
* chmod +x forgetSessions.php
*
* For a dry run set "DEBUG = true" below and watch all the session names go by.
* For cron use consider setting "OUTPUT = false" to suppress success message,
* only errors will be reported.
*/
const OUTPUT = true;
const DEBUG = false;
// make sure path is correct for your store
// this assumes script is in store root
define('SESSION_PATH', __DIR__ . '/var/session');
// this should match PHP's native naming
// change only if server is configured to name differently
define('SESSION_PATTERN', 'sess_*');
// only process files older than this time
// 3600 seconds = 1 hour
define('EXPIRY_LIMIT', time() - 3600);
// no time limit because this might be a big job
set_time_limit(0);
// this loads user data, writes a cookie, etc.
// must restore afterwards or data will be damaged
session_start();
$preserved_sess = $_SESSION;
// declare plain text for browser use
// CLI is unaffected
if (! headers_sent()) {
header('Content-Type: text/plain');
}
// useful stats
$count_sess = 0;
$count_unlinks = 0;
// iterate instead of glob in case there are a lot of files to scan
$dir = new DirectoryIterator(SESSION_PATH);
foreach ($dir as $file) {
// ignore sub-directories
if ($file->isDir()) continue;
// reject non-session files
if (! fnmatch(SESSION_PATTERN, $file->getFilename())) continue;
// reject recently modified files
if (EXPIRY_LIMIT < $file->getMTime()) {
if (DEBUG) echo $file->getFilename(), ' - Skip', PHP_EOL;
continue;
}
// overwrite $_SESSION var
if (session_decode(file_get_contents($file->getPathname()))) {
$count_sess++;
// suppress null pointer error in case key is not set
$rememberme = @$_SESSION['rememberme'];
if ($rememberme) {
if (! DEBUG) unlink($file->getFilename());
$count_unlinks++;
}
if (DEBUG) echo $file->getFilename(), ($rememberme ? ' - Remember' : ' - Forget' ), PHP_EOL;
}
}
// be responsible in case user has a real session to protect
if (function_exists('session_abort')) {
session_abort();
}
else {
$_SESSION = $preserved_sess;
}
if (OUTPUT) {
echo 'Sessions read: ', $count_sess, PHP_EOL;
echo 'Sessions removed: ', $count_unlinks, PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment