How can a PHP session be automatically destroyed after a certain time of inactivity?
To automatically destroy a PHP session after a certain time of inactivity, you can set a timeout period for the session. This can be achieved by setting the session.gc_maxlifetime directive in the php.ini file or by using the session_set_cookie_params() function in your PHP code.
// Set session timeout to 30 minutes
ini_set('session.gc_maxlifetime', 1800);
// Start the session
session_start();
// Check if last activity timestamp is set
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > 1800)) {
// Destroy the session if inactive for more than 30 minutes
session_unset();
session_destroy();
}
// Update last activity timestamp
$_SESSION['last_activity'] = time();