Use this file at the top of every PHP page (before any output):
🧩 What This Does
✅ Stores session files in /sessions/ folder.
✅ Automatically deletes files older than 8 hours (every time a session starts).
✅ Ensures PHP’s garbage collection also respects 8-hour lifetime.
✅ Fully standalone — no cron job or database needed.
<?php
// Folder to store sessions
$sessionPath = __DIR__ . '/sessions';
// Create folder if not exists
if (!is_dir($sessionPath)) {
mkdir($sessionPath, 0700, true);
}
// Set PHP to use this folder for session files
ini_set('session.save_path', $sessionPath);
// Delete old session files (older than 8 hours = 28800 seconds)
$files = glob($sessionPath . '/sess_*');
$now = time();
foreach ($files as $file) {
if (is_file($file) && ($now - filemtime($file)) > 28800) { // 8 hours
unlink($file);
}
}
// Set session lifetime (for garbage collection)
ini_set('session.gc_maxlifetime', 28800); // 8 hours
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 1);
// Start the session
session_start();
?>

0 Comments