How to set session time out in PHP

How to set session time out in PHP

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

Stefan Bogdanescu

Founder & Senior Architect

How to set session time out in PHP

Session timeouts are a critical component of application security, yet they often remain misunderstood or poorly implemented. Developers frequently confuse the server-side timeout configuration with actual user behavior, such as closing a browser tab or leaving a page idle. To build a secure and usable experience, you need to distinguish between these scenarios and apply the correct mechanisms for each.

Server-Side Timeout Configuration

The most common approach involves configuring the PHP runtime to automatically destroy sessions after a period of inactivity. This is controlled by two specific constants: session.gc_maxlifetime and session.cookie_lifetime.

You can set the garbage collection interval, which determines how often expired session data is removed from storage, in the php.ini file or within your application logic using the ini_set() function. However, setting session.gc_maxlifetime alone is insufficient. This value defines how long a session file remains valid on the server side. If your cookie lifetime does not match this duration, you risk creating orphaned sessions or prematurely logging users out.

To align these settings in your application code, ensure you execute the following logic early in your request lifecycle:

<?php
session_start();

// Set session to last 1 hour if inactive
ini_set('session.gc_maxlifetime', 3600);
ini_set('session.cookie_lifetime', 3600);

// Update the session cookie to reflect the new lifetime
session_set_cookie_params([
    'lifetime' => 3600,
    'path' => '/',
    'domain' => $_SERVER['HTTP_HOST'],
    'secure' => true, // Only set true if using HTTPS
    'httponly' => true,
    'samesite' => 'Lax'
]);

// Regenerate session ID to prevent fixation attacks during configuration change
session_regenerate_id(true);
?>

This approach ensures that the server considers a session invalid after one hour of no activity. When PHP's garbage collector runs (or when you manually destroy the session), it will clean up data older than this threshold.

Handling Browser Closures and Tab Closing

A frequent misconception is that PHP sessions automatically expire when a user closes their browser tab. By default, PHP does not detect when a client disconnects or closes a window. Session expiration relies entirely on the server checking the "last touch" timestamp stored in the session data. Consequently, if a user opens a tab, navigates away, and then reopens it months later without logging out, the session might still be valid unless the garbage collector has run since their last activity.

To address this, you must rely on cookie expiration settings. If your session.cookie_lifetime is set to 0 (the default), the session becomes invalid immediately after the browser closes. However, if you have configured a non-zero lifetime for session.cookie_lifetime, the session will persist across browser restarts until that specific time window elapses.

If your application requires immediate logout upon browser closure without waiting for the garbage collector cycle, you must implement client-side logic to notify the server when the user leaves. This typically involves sending an HTTP request to a dedicated route or API endpoint as soon as the user navigates away from the current page. You can achieve this by listening for the beforeunload event in JavaScript:

window.addEventListener('beforeunload', function() {
    // Send a silent request to invalidate the session
    fetch('/logout-trigger', { method: 'POST' })
        .catch(err => console.error(err));
});

The server endpoint /logout-trigger should simply call session_destroy() upon receiving the request. This pattern provides immediate security by ensuring that no active session exists once the user leaves the site, regardless of your gc_maxlifetime configuration.

Trade-offs and Best Practices

Relying solely on session.gc_maxlifetime introduces a race condition where users might be logged out unexpectedly if the garbage collector runs while they are still attempting to interact with the application. Conversely, relying entirely on client-side notifications fails silently if the JavaScript fails to load or if the user closes the tab without triggering the event listener.

For high-security applications, a hybrid approach is often necessary. Configure session.gc_maxlifetime as a hard limit for data retention in storage databases like Redis or Memcached, but implement the beforeunload logic to ensure immediate invalidation upon navigation. Remember that setting session.cookie_lifetime to a non-zero value extends the session validity beyond the current browsing session if the user returns later within that window, which may be undesirable for sensitive operations.

When deploying these configurations, always consider the environment. In shared hosting environments where you cannot modify php.ini, using ini_set() is mandatory. Furthermore, ensure that session.cookie_secure is set to true and that your application is served over HTTPS; otherwise, browsers will ignore the secure cookie settings, potentially exposing session tokens over unencrypted connections.

Our network