Users are logged out of a PHP session after a short idle time
User is sent back to the login page after roughly 24 minutes without activityShort answer
A PHP session lives in two places with two clocks: the data file on the server, cleaned up after session.gc_maxlifetime (1440 seconds by default), and the cookie in the browser. To keep idle users logged in, raise gc_maxlifetime, give the cookie a lifetime, keep your own save_path, and enforce the idle limit with a timestamp in your own code.
Fix it fast
1Find out which cause you have
Print the session values PHP is using, including where session files go. This command reads the CLI settings; run the same ini_get() calls from a web page to see what Apache or FPM uses.
php -r 'foreach (["session.gc_maxlifetime","session.cookie_lifetime","session.gc_probability","session.gc_divisor","session.save_path"] as $k) echo $k, " = ", ini_get($k), PHP_EOL;'2Match what you see, then jump to its fix
- 1
The output above shows session.gc_maxlifetime = 1440gc_maxlifetime is still the default 1440 secondsFix - 2
Sessions vanish earlier than your own setting, and other PHP apps run on the same server using the same session.save_pathAnother script shares the save path and cleans with a shorter lifetimeFix - 3
The session ends when the browser closes, or the cookie expires after a fixed time even for active usersThe cookie ends with the browser, or its expiry is never renewedFix
- 1
What does the error look like?
User is sent back to the login page after roughly 24 minutes without activity$_SESSION is empty on the next request although the browser still sends the session cookie
Cause 1 of 3
gc_maxlifetime is still the default 1440 seconds
1Check
Session data older than gc_maxlifetime counts as garbage and may be removed. Cleanup is probabilistic, 1 chance in 100 per session start with the defaults, so expiry looks irregular on a quiet site.
php -r 'echo ini_get("session.gc_maxlifetime"), PHP_EOL;'2Fix
Set a longer value before session_start(). Do not rely on it alone: the manual recommends tracking the session lifetime with a timestamp you store yourself.
ini_set('session.gc_maxlifetime', '7200');
session_start();
$limit = 7200;
if (isset($_SESSION['last_seen']) && time() - $_SESSION['last_seen'] > $limit) {
session_unset();
session_destroy();
header('Location: /login.php');
exit;
}
$_SESSION['last_seen'] = time();3Verify
Log in, wait past the old limit, and load a page again while still inside your new limit.
php -d session.gc_maxlifetime=7200 -r 'echo ini_get("session.gc_maxlifetime"), PHP_EOL;'Confirmed by php.net
Cause 2 of 3
Another script shares the save path and cleans with a shorter lifetime
1Check
If scripts with different gc_maxlifetime values share one storage place, the script with the smallest value cleans the data of all of them.
php -r 'echo ini_get("session.save_path"), PHP_EOL;'2Fix
Give each application its own session.save_path, in a directory that is not world-readable.
ini_set('session.save_path', '/var/lib/php/app_sessions');
session_start();3Verify
Create the directory writable by the PHP user, log in again and check a session file appears there.
ls -l /var/lib/php/app_sessionsConfirmed by php.net
Cause 3 of 3
The cookie ends with the browser, or its expiry is never renewed
1Check
session.cookie_lifetime = 0 means the cookie lasts until the browser closes. Calling session_set_cookie_params() applies only to the current script and the expiry is not refreshed on later visits by itself.
php -r 'echo ini_get("session.cookie_lifetime"), PHP_EOL;'2Fix
Set the cookie parameters before session_start() on every request, and resend the cookie after starting the session so the expiry slides forward with activity.
$life = 7200;
session_set_cookie_params(['lifetime' => $life, 'path' => '/', 'httponly' => true]);
session_start();
setcookie(session_name(), session_id(), time() + $life, '/');3Verify
Open the browser's cookie list and see that the session cookie has an expiry about two hours ahead after each request.
curl -s -I -c - https://example.com/ | grep -i set-cookieConfirmed by php.net
How do I stop it coming back?
- Store a last-activity timestamp in the session and decide expiry in your code, not by file cleanup.
- Use a dedicated session.save_path for each app, outside /tmp.
- Run session_gc() from cron if you use a custom save path with a depth argument, because automatic cleanup is off then.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Back end
Android gets HTML instead of JSON from a PHP API
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
The response body is not JSON.
2 causes, each with a fixBack end
Apache returns 403 when a URL contains %3F
a request like /page%3Fname=test is refused while /page?name=test works
Recent Apache httpd blocks a rewrite when the request contains an encoded question mark (%3F) and the rewritten target has a literal ?.
2 causes, each with a fixBack end
Apache returns 500 with Premature end of script headers
500 Internal Server Error
Apache ran your script, but the script printed no valid HTTP header before its output.
3 causes, each with a fixBack end
Apache returns 503 or 504 because PHP-FPM did not answer in time
Error dispatching request
Apache sent the request to PHP-FPM and gave up waiting.
3 causes, each with a fixBack end
AWS SDK for PHP cannot get credentials from the instance profile metadata server
Error retrieving credentials from the instance profile metadata server.
The SDK tries the EC2 instance metadata service when it has no valid credentials from anywhere earlier in its chain.
4 causes, each with a fixBack end
AWS SDK for PHP rejects requests: the signature is from the future
Signature not yet current: {date} is still later than {date}
AWS compares the timestamp in your signed request with its own clock.
2 causes, each with a fix