What best practices can be implemented to accurately track and manage session timeouts in PHP?
Session timeouts in PHP can be accurately tracked and managed by setting the session.gc_maxlifetime value in the php.ini file to the desired session timeout period in seconds. Additionally, developers can implement a custom session timeout handler to alert users before their session expires, giving them the option to extend their session.
// Set the session timeout to 30 minutes (1800 seconds)
ini_set('session.gc_maxlifetime', 1800);
// Custom session timeout handler
function check_session_timeout() {
if (isset($_SESSION['last_activity']) && time() - $_SESSION['last_activity'] > $_SESSION['timeout']) {
// Session expired, destroy session and redirect to login page
session_unset();
session_destroy();
header('Location: login.php');
exit;
} else {
$_SESSION['last_activity'] = time();
}
}
// Set session timeout and start session
session_start();
// Set session timeout period in seconds
$_SESSION['timeout'] = 1800; // 30 minutes
// Call the session timeout handler on every page load
check_session_timeout();