How can session garbage collection be implemented efficiently in PHP to remove expired sessions?

Session garbage collection in PHP can be implemented efficiently by setting the session.gc_probability and session.gc_divisor values appropriately in the php.ini file. These values determine the probability of garbage collection being triggered on each session start. Additionally, you can create a custom garbage collection script that runs periodically to remove expired sessions based on their last activity timestamp.

// Custom garbage collection script to remove expired sessions
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);

session_start();

// Set the maximum session lifetime
$maxLifetime = ini_get('session.gc_maxlifetime');

// Iterate through all sessions and remove expired ones
foreach (glob(session_save_path() . '/*') as $file) {
    if (file_exists($file) && time() - filemtime($file) > $maxLifetime) {
        unlink($file);
    }
}