What are the best practices for handling session expiration in PHP to ensure security and efficiency?
Session expiration is crucial for security as it helps prevent unauthorized access to sensitive information. To handle session expiration in PHP, it is recommended to set a reasonable session timeout period, regenerate session IDs after a certain period of inactivity, and destroy the session data upon logout or timeout.
// Set session timeout period to 30 minutes
ini_set('session.gc_maxlifetime', 1800);
// Regenerate session ID after 30 minutes of inactivity
if (isset($_SESSION['LAST_ACTIVITY']) && time() - $_SESSION['LAST_ACTIVITY'] > 1800) {
session_regenerate_id(true);
$_SESSION['LAST_ACTIVITY'] = time();
}
// Destroy session data upon logout or timeout
if (isset($_SESSION['LAST_ACTIVITY']) && time() - $_SESSION['LAST_ACTIVITY'] > 1800) {
session_unset();
session_destroy();
}