What is the best practice for cleaning up temporary files created during a PHP session?

When using PHP sessions, temporary files are created to store session data on the server. To clean up these temporary files, you can use a cron job or a PHP script that deletes old session files periodically. This helps to free up server space and maintain system performance.

// Clean up old session files
$sessionPath = session_save_path(); // Get the path to the session files
$sessionLifetime = ini_get('session.gc_maxlifetime'); // Get the session lifetime
$currentTime = time(); // Get the current time

foreach (glob("$sessionPath/sess_*") as $file) {
    if (filemtime($file) + $sessionLifetime < $currentTime) {
        unlink($file); // Delete session file if it has expired
    }
}