How do I expire a PHP session after 30 minutes?
Setting a specific expiration time for a PHP session is a common requirement when you need to enforce a "idle timeout" or ensure sensitive data isn't retained indefinitely in server memory. The core mechanism relies on the session.gc_maxlifetime directive, which dictates how long the session file persists on the filesystem before the garbage collector considers it abandoned.
To configure a 30-minute expiration, you must set this value explicitly. In your php.ini, locate or add the following line:
session.gc_maxlifetime = 1800
The value 1800 represents seconds (30 minutes x 60). However, setting the configuration file alone is rarely sufficient if you are relying solely on server-side timers. The PHP garbage collector runs probabilistically; it doesn't check every second to see if a session has exceeded the limit. It only runs when session.gc_probability and session.gc_divisor dictate. By default, gc_probability is 1 and gc_divisor is 100, meaning there is roughly a 1% chance the GC will run on each script execution.
If you require a hard expiration after exactly 30 minutes of inactivity, relying solely on session.gc_maxlifetime introduces a window where a user could technically keep a session alive for up to 30 minutes plus one full garbage collection cycle duration (which can be several seconds or even longer if the server is under load). For high-security applications, this probabilistic nature is often unacceptable.
The robust solution involves manually destroying the session once the timeout period has elapsed. You should implement a timer logic that checks the last activity timestamp against the current time. If the difference exceeds 30 minutes (1800 seconds), you explicitly call session_destroy().
Here is a practical implementation pattern using a session-based timer:
// At the start of your application or middleware
$timeout = 1800; // 30 minutes in seconds
if (!isset($_SESSION['last_activity'])) {
$_SESSION['last_activity'] = time();
} else {
$lastActivity = $_SESSION['last_activity'];
if ((time() - $lastActivity) > $timeout) {
session_destroy();
// Redirect to login or handle the timeout logic here
header('Location: /login');
exit;
}
}
// Update the activity timestamp at the end of every request or action
$_SESSION['last_activity'] = time();
This approach guarantees that if a user leaves the application idle for 30 minutes, the session is forcibly terminated on the next request. It removes any ambiguity regarding server load or garbage collection settings.
There are trade-offs to consider with this method. The primary one is performance overhead. Every request requires calculating the time difference and updating the last_activity variable in the session array. While negligible for most applications, this adds a write operation to the session storage on every interaction. If you are using a high-performance file-based storage or a database backend, ensure your session handler can handle frequent updates without locking issues.
Another consideration is cross-device consistency. If a user logs into multiple devices, updating the last_activity timestamp on one device resets the timer for all of them. This is often desirable for security (preventing long-term access from any single point of failure), but you must ensure your logic aligns with your specific threat model.
If you are working within the Laravel ecosystem, this pattern is easily integrated into middleware or service providers to enforce global timeouts without modifying every controller. For more advanced needs, such as handling sessions stored in Redis or Memcached, the session.gc_maxlifetime directive becomes irrelevant because those backends manage TTLs independently. In those cases, you would configure a key expiration time within your cache driver settings rather than relying on PHP's session garbage collection logic.
When implementing manual expiration, always ensure you handle the cleanup gracefully. Simply calling session_destroy() removes the session from the array and marks it for deletion by the GC, but it does not immediately delete the file or cache entry if using a backend like Redis. You might need to explicitly invalidate the session key in your cache store after destroying the PHP session data to prevent potential race conditions where a subsequent request tries to read a stale session token before the cache entry expires naturally.