Home >Backend Development >PHP Tutorial >How Can I Control Session Timeouts in PHP?
When working with PHP, you may encounter the need to adjust the default session timeout settings. While php.ini modifications offer a solution, limited access to this file may prompt you to seek alternative methods.
To enforce a strict upper bound on session inactivity, we can implement custom logic that stores this bound within the session data:
session_start(); $now = time(); if (isset($_SESSION['discard_after']) && $now > $_SESSION['discard_after']) { // Session has expired, destroy and start a new one session_unset(); session_destroy(); session_start(); } // Set expiration time for both new and existing sessions $_SESSION['discard_after'] = $now + 3600;
If imposing a strict limit is unnecessary, you can rely on specific PHP configuration parameters to establish a lower bound:
// Server retains session data for at least 1 hour ini_set('session.gc_maxlifetime', 3600); // Clients retain session ID for exactly 1 hour session_set_cookie_params(3600); session_start();
This approach instructs the server to store session data for a minimum of one hour and clients to discard their session ID after the same duration.
When imposing session timeouts, it's crucial to address both client-side and server-side settings. For maximum control and predictability, combine a strict upper bound with session.gc_maxlifetime's lower bound. However, be aware that session ID preservation may warrant attention, especially if its value is sensitive.
The above is the detailed content of How Can I Control Session Timeouts in PHP?. For more information, please follow other related articles on the PHP Chinese website!