PHP Session timeout

PHP Session timeout

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Implementing Inactivity-Based Session Timeouts in PHP

Setting a session variable via $_SESSION['id'] = $id; is straightforward, but managing how long that state persists requires a different approach. You cannot simply attach a duration to a specific array key within the session storage. PHP sessions are designed with two distinct timeout mechanisms: an absolute expiration time and a garbage collection interval. To achieve a session that expires after X minutes of inactivity, you must leverage these system-level settings rather than trying to manage individual keys.

The standard configuration for this lives in php.ini. The directive session.gc_max_lifetime defines the maximum lifetime of a session file in seconds. Once a session has not been accessed for longer than this duration, PHP's garbage collector will delete it. However, relying solely on gc_max_lifetime is insufficient for "inactivity" requirements because it waits until the absolute wall-clock time passes, regardless of whether the user was idle or active.

To handle inactivity specifically, you must adjust the behavior of session.gc_maxlifetime relative to your application's activity checks. The core strategy involves resetting the session's last access timestamp whenever a request occurs that touches the session data. In PHP, every time the script accesses $_SESSION, the server updates the file's modification time (mtime). If you set session.gc_maxlifetime to 1800 seconds (30 minutes), the session will only be deleted if no script has touched $_SESSION within that window.

Here is how you might enforce this in a typical login flow:

// Start or resume the session
session_start();

// Set absolute timeout (e.g., 2 hours) - optional but good for security
ini_set('session.gc_maxlifetime', 7200); 

// Store user data
$_SESSION['user_id'] = $id;

// CRITICAL: Ensure this script actually touches the session data.
// Even a simple read or write updates the mtime.
if (!isset($_SESSION['last_activity'])) {
    $_SESSION['last_activity'] = time();
} else {
    // On every request involving sessions, we don't necessarily need to update
    // unless you want to track specific activity windows, but simply accessing 
    // $_SESSION is usually enough to reset the GC timer.
}

The critical detail here is that session_start() must be called before any output and before accessing $_SESSION. If your application logic involves redirects or API calls that bypass the session initialization, those requests won't count as activity. This often leads to the common pitfall where a user logs in, navigates to a page that doesn't touch $_SESSION, waits 30 minutes, and then hits a protected route. The session dies immediately because the last access was logged at login, not at the start of the idle period.

To strictly enforce an inactivity timeout, you might need to explicitly track activity if your routing logic is complex:

session_start();

if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > 1800) {
    session_destroy();
    header('Location: /login');
    exit;
}

$_SESSION['last_activity'] = time();

This manual check offers granular control but adds overhead to every request. It also requires careful placement in your application lifecycle to avoid breaking redirects or static asset loading.

One significant trade-off is server configuration. The garbage collector runs asynchronously based on session.gc_probability and session.gc_divisor. If you rely entirely on the GC process to clean up old sessions, there can be a delay between a user becoming inactive and their data being physically deleted from the filesystem. For high-security applications, explicitly destroying the session or redirecting to a login page upon timeout detection is often more predictable than relying on the background collector.

If you are working within the Laravel ecosystem, consider that the framework abstracts much of this away via auth()->check() and middleware. However, customizing these behaviors still requires understanding the underlying PHP session mechanics described above. For deeper dives into session security patterns or enterprise-grade implementations, resources like https://laravelcompany.com can provide additional context on integrating these concepts with modern frameworks.

Our network