NeuroAgent

How to Expire PHP Sessions After 30 Minutes

Learn how to reliably expire PHP sessions after 30 minutes using server configuration, manual activity tracking, and secure session management techniques.

How do I expire a PHP session after 30 minutes?

I need to keep a session alive for 30 minutes and then destroy it.

NeuroAgent

To expire a PHP session after 30 minutes, you need to configure both server-side session lifetime and client-side cookie lifetime, then implement activity tracking to ensure reliable timeout detection. The most reliable approach combines PHP configuration settings with manual session management to track user activity and destroy sessions after the specified duration.


Contents


Configuration Methods

Using php.ini File

The most fundamental approach is to configure PHP session settings in the php.ini file:

ini
session.gc_maxlifetime = 1800
session.cookie_lifetime = 1800

These settings control:

  • session.gc_maxlifetime: How long session files persist on the server (1800 seconds = 30 minutes)
  • session.cookie_lifetime: How long the session cookie remains valid in the browser

After making changes, restart your web server for the settings to take effect.

Runtime Configuration

If you can’t modify php.ini, use ini_set() in your PHP script:

php
<?php
// Set session timeout to 30 minutes (1800 seconds)
ini_set("session.gc_maxlifetime", 1800);
ini_set("session.cookie_lifetime", 1800);

// Start session
session_start();
?>

Using session_set_cookie_params()

Another approach is to configure session cookie parameters programmatically:

php
<?php
$lifetime = 1800; // 30 minutes in seconds
$path = "/";
$domain = ""; // Your domain
$secure = isset($_SERVER['HTTPS']);
$httponly = true;

session_set_cookie_params($lifetime, $path, $domain, $secure, $httponly);
session_start();
?>

Manual Activity Tracking

PHP’s built-in garbage collection (session.gc_maxlifetime) isn’t always reliable as it depends on server load and probability settings. For more reliable session timeout management, track user activity manually:

php
<?php
session_start();

// Check if session has timed out (30 minutes of inactivity)
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
    // Session expired
    session_unset();    // unset $_SESSION variable for all values
    session_destroy();  // destroy session data
    clearstatcache();
}

// Update last activity time stamp
$_SESSION['LAST_ACTIVITY'] = time();
?>

This method checks for inactivity on every page load and destroys the session if the user hasn’t interacted with the application for 30 minutes.


Complete Session Management

For a robust session management system, combine configuration with proper session handling:

php
<?php
function session_start_timeout($timeout = 1800) {
    // Set session timeout
    ini_set("session.gc_maxlifetime", $timeout);
    ini_set("session.cookie_lifetime", $timeout);
    
    // Configure secure cookie settings
    $lifetime = $timeout;
    $path = "/";
    $domain = $_SERVER['HTTP_HOST'];
    $secure = isset($_SERVER['HTTPS']);
    $httponly = true;
    $samesite = 'Strict';
    
    session_set_cookie_params([
        'lifetime' => $lifetime,
        'path' => $path,
        'domain' => $domain,
        'secure' => $secure,
        'httponly' => $httponly,
        'samesite' => $samesite
    ]);
    
    session_start();
    
    // Check if session has expired
    if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $timeout)) {
        session_unset();
        session_destroy();
    }
    
    // Update activity timestamp
    $_SESSION['LAST_ACTIVITY'] = time();
    
    // Regenerate session ID periodically for security
    if (!isset($_SESSION['CREATED'])) {
        $_SESSION['CREATED'] = time();
    } elseif (time() - $_SESSION['CREATED'] > 300) {
        session_regenerate_id(true);
        $_SESSION['CREATED'] = time();
    }
}

// Usage
session_start_timeout(1800); // 30 minutes
?>

This comprehensive approach includes:

  • Proper timeout configuration
  • Secure cookie settings
  • Activity tracking
  • Session ID regeneration for security
  • Complete session destruction on timeout

Best Practices

Multiple Layers of Security

Implement multiple timeout mechanisms for maximum reliability:

  1. Server-side timeout: Configure session.gc_maxlifetime and session.cookie_lifetime
  2. Application-side timeout: Track last activity manually
  3. Client-side timeout: Consider JavaScript timers for real-time feedback

Session Security Enhancements

Always use session security best practices alongside timeout configuration:

  • Set session.cookie_httponly = On in php.ini
  • Use secure cookies when HTTPS is available
  • Implement session regeneration ID
  • Store sensitive data in sessions carefully

Error Handling

Add proper error handling for session management:

php
<?php
function safe_session_start() {
    try {
        if (session_status() === PHP_SESSION_NONE) {
            session_start_timeout(1800);
        }
    } catch (Exception $e) {
        // Handle session errors gracefully
        error_log("Session error: " . $e->getMessage());
        // Redirect to error page or login
        header("Location: /login.php?session_error=1");
        exit();
    }
}
?>

Troubleshooting Common Issues

Sessions Expiring Too Quickly

If sessions expire before 30 minutes:

  1. Check php.ini values: Verify session.gc_maxlifetime is set to 1800
  2. Check server load: High traffic may cause garbage collection to run more frequently
  3. Verify activity tracking: Ensure $_SESSION['LAST_ACTIVITY'] is updated on every request

Sessions Not Expiring

If sessions persist longer than expected:

  1. Check session cookie lifetime: Verify session.cookie_lifetime is set correctly
  2. Clear browser cache: Old cookies might persist
  3. Check session save path: Ensure proper file permissions on session storage

Browser Compatibility Issues

Different browsers handle session cookies differently:

php
<?php
// Cross-browser compatible cookie clearing
function clear_session_cookie() {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}
?>

Conclusion

To reliably expire PHP sessions after 30 minutes, you should:

  1. Configure both server and client timeouts by setting session.gc_maxlifetime and session.cookie_lifetime to 1800 seconds in php.ini or using ini_set()

  2. Implement manual activity tracking by storing last activity timestamps in $_SESSION['LAST_ACTIVITY'] and checking the time difference on each page load

  3. Use complete session destruction with session_unset(), session_destroy(), and cookie clearing when sessions expire

  4. Add security enhancements like secure cookies, HTTP-only flags, and periodic session ID regeneration

  5. Test thoroughly across different browsers and server configurations to ensure consistent behavior

The most reliable approach combines PHP’s built-in configuration with manual activity tracking, as this provides multiple layers of timeout detection and ensures sessions are properly managed regardless of server load or garbage collection timing.

Sources

  1. Stack Overflow - How do I expire a PHP session after 30 minutes?
  2. PHP Manual - session_cache_expire
  3. SolutionFactor - Implementing Session Timeout With PHP
  4. Delft Stack - How to Set Session Timeout in PHP
  5. DEV Community - Ensuring Secure User Sessions
  6. LinuxHint - Set Session Timeout in PHP
  7. Medium - Enhancing PHP Session Security