How to set lifetime of session

How to set lifetime of session

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

Stefan Bogdanescu

Founder & Senior Architect

How to Set Session Lifetime in PHP for Long-Running AJAX Requests

You are encountering the default behavior of PHP's session garbage collector. By default, session.gc_maxlifetime is set to 1800 seconds (30 minutes), but your environment might be configured conservatively or you might be relying on a specific server setting that defaults to 300 seconds. When you run an AJAX request every 10 seconds without explicitly managing the session timeout, PHP will eventually purge the $_SESSION array if it deems the session stale based on the last activity timestamp.

The core issue in your current setup is that session_start() initializes the session, but it does not inherently "refresh" the expiration time to the current moment unless you explicitly tell PHP to do so. In many configurations, the session is marked as active, but the underlying garbage collector runs independently based on the gc_maxlifetime directive and the last_accessed timestamp stored in the session file (or database, depending on your storage driver).

To achieve a "forever" session where the data persists as long as the request exists, you need to modify the session metadata directly. The most reliable way to ensure the session does not expire while your JavaScript polls every 10 seconds is to use session_regenerate_id(true) or simply update the last_access_time logic, but the cleanest approach for "forever" sessions in a stateless AJAX context is often to bypass the standard file-based expiration if possible, or force the regeneration.

However, there is a simpler architectural fix that aligns with your specific code: ensuring the session is marked as active every time it is accessed. While session_start() loads the data, simply reading from $_SESSION in PHP (like $_SESSION['counter'] += 1) technically updates the last access time in the file metadata if the storage driver supports it natively and if the web server allows the file to be touched. If you are using standard file sessions, the increment operation should update the timestamp.

If you find that the session is still expiring after the increment, it is likely because the garbage collector has already marked the file for deletion before the next request arrives, or your gc_probability and gc_divisor settings are too aggressive relative to your low traffic frequency. To hard-set a "forever" lifetime, you can set the session.gc_maxlifetime directive in your php.ini file to a very large number:

session.gc_maxlifetime = 31536000 ; One year

This prevents the default cleanup routine from deleting sessions after 300 seconds. However, setting this globally is not always ideal for security reasons, as it leaves open sessions vulnerable to fixation attacks if not handled carefully. A more targeted approach for your specific AJAX use case is to regenerate the session ID and ensure the session is persisted correctly on every tick.

In your ajax.php, you can force the session to be treated as new and active by using session_regenerate_id(false). This keeps the old ID but updates the timestamp, effectively resetting the timer for the garbage collector:

<?php
// AJAX.php
session_start();
session_regenerate_id(false); // Updates the last accessed time without changing the ID

$_SESSION['counter'] = $_SESSION['counter'] + 1;

header('Content-type: application/json');    
echo json_encode(array('tick' => $_SESSION['counter']));
?>

Alternatively, if you are using Laravel (as suggested by the context of modern PHP frameworks), you can access the session facade to manipulate these values. If you require a "forever" session specifically within a Laravel application, you should configure the session.lifetime in your config/session.php file:

'sessions' => [
    'driver' => 'file', // Or database/redis for better scalability
    'lifetime' => 0,   // 0 means "until browser closes" or until explicitly destroyed
],

Setting lifetime to 0 tells the framework not to expire the session automatically. This is often cleaner than tweaking low-level PHP directives. However, be aware that setting a lifetime of 0 might conflict with specific middleware logic that expects sessions to expire after a certain period for security audits.

Trade-offs and Pitfalls

The primary trade-off here is security versus convenience. A session that never expires increases the risk of session fixation if an attacker can predict or manipulate the timing of your AJAX calls. If you set lifetime to 0, ensure that your application logic explicitly destroys sessions (session_destroy()) when a user logs out or when the connection terminates unexpectedly.

Another common mistake is relying solely on $_SESSION['counter'] = $_SESSION['counter'] + 1. While this updates the variable, it relies on the underlying storage driver updating the file timestamp correctly. If you are using Redis as a session store (recommended for high-frequency AJAX apps), PHP handles the TTL logic differently via the Redis connection. In that case, you might need to explicitly set the expiration in your code:

// Only relevant if using Redis or similar drivers with manual TTL control
session_start();
$_SESSION['counter'] = $_SESSION['counter'] + 1;
// No automatic expiration needed if driver supports it, but check specific config

For standard file-based sessions, the session_regenerate_id(false) approach combined with a high gc_maxlifetime is the most robust solution to prevent the 300-second cutoff without changing the global application behavior for non-AJAX users. If you are using Laravel, stick to the configuration file approach as it encapsulates the logic cleanly.

Our network