How do I expire a PHP session after 30 minutes?

To expire a PHP session after 30 minutes of inactivity, follow these steps:

1. Configure Session Settings

  • Set Cookie Parameters: Define secure cookie settings and optional expiration.
  • Adjust Garbage Collection: Ensure the server retains session data for at least 30 minutes.

2. Track Last Activity

  • Store a timestamp (last_activity) in the session to track user interaction.
  • Check this timestamp on each request to determine if the session has expired.

3. Update and Validate Session

  • Update Timestamp: Refresh last_activity on every request.
  • Regenerate Session ID: Periodically refresh the session ID for security.

Example Code

<?php
// Set secure session cookie parameters
session_set_cookie_params([
    'lifetime' => 0,              // Expire when the browser closes
    'path' => '/',
    'domain' => $_SERVER['HTTP_HOST'],
    'secure' => true,            // Requires HTTPS
    'httponly' => true,          // Prevent JavaScript access
    'samesite' => 'Strict'       // Mitigate CSRF attacks
]);

// Server-side session data retention (30 minutes)
ini_set('session.gc_maxlifetime', 1800);

// Start the session
session_start();

// Check if the session has expired due to inactivity
if (isset($_SESSION['last_activity']) {
    $inactive = time() - $_SESSION['last_activity'];
    if ($inactive > 1800) { // 30 minutes in seconds
        // Destroy the session and redirect
        session_unset();
        session_destroy();
        header('Location: login.php?expired=1');
        exit();
    }
} else {
    // Initialize last activity time
    $_SESSION['last_activity'] = time();
}

// Update last activity time on each request
$_SESSION['last_activity'] = time();

// Regenerate session ID every 30 minutes to prevent fixation
if (!isset($_SESSION['created'])) {
    $_SESSION['created'] = time();
} elseif (time() - $_SESSION['created'] > 1800) {
    session_regenerate_id(true); // Destroy old session
    $_SESSION['created'] = time();
}
?>

Explanation

  1. Cookie Configuration:
  • session_set_cookie_params() sets secure cookie attributes. lifetime: 0 ensures the cookie expires when the browser closes. Adjust this if you want the cookie to persist longer.
  1. Garbage Collection:
  • ini_set('session.gc_maxlifetime', 1800) tells the server to keep session data for 30 minutes before deletion.
  1. Activity Tracking:
  • last_activity is updated on every request. If 30 minutes pass without activity, the session is destroyed.
  1. Session Regeneration:
  • session_regenerate_id(true) prevents session fixation by creating a new ID and deleting the old one every 30 minutes.

Key Considerations

  • Security: Use HTTPS and secure cookie flags (secure, httponly, samesite).
  • Garbage Collection: Server cleanup depends on PHP’s session.gc_probability and session.gc_divisor. The activity check ensures immediate expiration regardless of GC.
  • Client-Side Cookies: If the browser’s session cookie expires, the user must reauthenticate even if server data exists.
  • Testing: Simulate expiration by temporarily reducing the 1800-second threshold.

Alternative Approach: Expire Session Exactly 30 Minutes After Login

To expire the session 30 minutes after creation (regardless of activity):

// At login:
$_SESSION['expire_time'] = time() + 1800;

// On subsequent requests:
if (isset($_SESSION['expire_time']) && time() > $_SESSION['expire_time']) {
    session_unset();
    session_destroy();
    header('Location: login.php');
    exit();
}

This method enforces a strict 30-minute lifespan from login, independent of user activity.

Leave a Reply

Your email address will not be published. Required fields are marked *