How do I expire a PHP session after 30 minutes?
I need to keep a session alive for 30 minutes and then destroy it.
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
- Manual Activity Tracking
- Complete Session Management
- Best Practices
- Troubleshooting Common Issues
Configuration Methods
Using php.ini File
The most fundamental approach is to configure PHP session settings in the php.ini file:
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
// 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
$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
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
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:
- Server-side timeout: Configure
session.gc_maxlifetimeandsession.cookie_lifetime - Application-side timeout: Track last activity manually
- 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 = Onin 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
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:
- Check php.ini values: Verify
session.gc_maxlifetimeis set to 1800 - Check server load: High traffic may cause garbage collection to run more frequently
- Verify activity tracking: Ensure
$_SESSION['LAST_ACTIVITY']is updated on every request
Sessions Not Expiring
If sessions persist longer than expected:
- Check session cookie lifetime: Verify
session.cookie_lifetimeis set correctly - Clear browser cache: Old cookies might persist
- Check session save path: Ensure proper file permissions on session storage
Browser Compatibility Issues
Different browsers handle session cookies differently:
<?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:
-
Configure both server and client timeouts by setting
session.gc_maxlifetimeandsession.cookie_lifetimeto 1800 seconds in php.ini or usingini_set() -
Implement manual activity tracking by storing last activity timestamps in
$_SESSION['LAST_ACTIVITY']and checking the time difference on each page load -
Use complete session destruction with
session_unset(),session_destroy(), and cookie clearing when sessions expire -
Add security enhancements like secure cookies, HTTP-only flags, and periodic session ID regeneration
-
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
- Stack Overflow - How do I expire a PHP session after 30 minutes?
- PHP Manual - session_cache_expire
- SolutionFactor - Implementing Session Timeout With PHP
- Delft Stack - How to Set Session Timeout in PHP
- DEV Community - Ensuring Secure User Sessions
- LinuxHint - Set Session Timeout in PHP
- Medium - Enhancing PHP Session Security