← Tous les articles

PHP Session Lost Between Pages (Login Not Sticking): Causes and Fixes

User logged out after a redirect, cart emptied, $_SESSION empty on the next page: a method to find the cause (code, cookie or server) and fix it.

PHP Session Lost Between Pages (Login Not Sticking): Causes and Fixes

Key points

  • A PHP session relies on a cookie: if the browser doesn’t send it back, or the server-side file disappears, the session is gone.
  • Causes fall into three groups: code order, cookie settings (domain, HTTPS, SameSite) and server-side storage.
  • A small diagnostic script tells you which group to look at within two page reloads.

The login form accepts the credentials, redirects to the account area… and the user lands back on the login page. Or the cart empties itself every now and then for no obvious reason. “The session keeps getting lost” is one of the most frustrating PHP problems, because it often works locally and breaks in production, or only for some users. The good news: there are only a handful of causes, and you can check them methodically.

How a session works (and where it can break)

On the first session_start(), PHP generates a random ID, sends it to the browser in a cookie (PHPSESSID by default) and creates a server-side file holding the contents of $_SESSION. On the next request, the browser sends the cookie back, PHP finds the file and reloads the data.

So a session can be lost in three places: the code doesn’t write the data (or not at the right moment), the browser doesn’t send the cookie back, or the server can’t find the file any more. This script, dropped temporarily on the server, tells you which within two reloads:

<?php
// debug-session.php: delete once you're done
session_start();
$_SESSION['counter'] = ( $_SESSION['counter'] ?? 0 ) + 1;

header( 'Content-Type: text/plain; charset=utf-8' );
echo 'Session ID: ', session_id(), "n";
echo 'Counter: ', $_SESSION['counter'], " (should go up on every reload)n";
echo 'Cookie received: ', $_COOKIE[ session_name() ] ?? 'NONE', "n";
echo 'save_path: ', session_save_path() ?: sys_get_temp_dir(), "n";
echo 'Directory writable: ', is_writable( session_save_path() ?: sys_get_temp_dir() ) ? 'yes' : 'NO', "n";
echo 'gc_maxlifetime: ', ini_get( 'session.gc_maxlifetime' ), " sn";
print_r( session_get_cookie_params() );
  • The ID changes on every reload: the cookie isn’t coming back. See the cookie causes below.
  • The ID is stable but the counter resets to 1: the server can’t find the data. See the server causes.
  • Everything works here but not in the app: the problem is in the code (next section).

In the browser dev tools, the Network tab completes the picture: check the Set-Cookie response header and the Cookie header of the following request. Chrome and Firefox also show, on hover, why a cookie was blocked.

Causes in the code

The most common one is session_start() called too late. It has to send an HTTP header, so it must come before any output: an echo, some HTML, a space or blank line before <?php, or the invisible BOM some editors add at the start of a file. PHP raises a “headers already sent” warning, but in production, with error display turned off, nobody sees it: check the error log.

Second cause: a page that forgets to call session_start(). There, $_SESSION is just an empty array. Put the call in a bootstrap file included everywhere instead of repeating it page by page.

Third, and subtler: redirecting right after writing. The correct pattern:

<?php
// login.php: session_start() BEFORE any output (even a space before <?php)
session_start();

if ( $_SERVER['REQUEST_METHOD'] === 'POST' && check_credentials( $_POST ) ) {
    session_regenerate_id( true );        // new ID after login
    $_SESSION['user_id'] = $user->id;
    session_write_close();                 // write the session before redirecting
    header( 'Location: /account' );
    exit;                                  // otherwise the script keeps running
}

The exit after header('Location: …') is essential: without it, the rest of the script runs and may change or clear the session. session_write_close() isn’t mandatory, since PHP writes the session at the end of the script, but it avoids surprises when the next page is requested before the previous one has finished.

That last point explains another symptom: AJAX requests that run one after another instead of in parallel. The default file handler locks the session for the whole duration of the script, so a long script holding it open blocks every other request from the same user. Call session_write_close() as soon as you no longer need to write, typically before heavy processing or an external API call.

Cookie causes: domain, HTTPS and SameSite

If the ID changes on every request, the browser isn’t sending the cookie back. The causes we see most:

  • www vs non-www. A cookie set on www.example.com isn’t sent to example.com. If the form posts to one and redirects to the other, the session looks lost. Always redirect to a single version of the domain.
  • A secure cookie on an HTTP page. A cookie flagged secure only travels over HTTPS. Typical case: production runs on HTTPS, staging or the local machine on HTTP, with the same config.
  • SameSite. Browsers treat a cookie without a SameSite attribute as Lax: it isn’t sent on requests coming from another site, such as a POST back from a payment page or an identity provider. Those flows need SameSite=None (with secure), or better, a GET return that doesn’t depend on the session to be validated.

Set the parameters explicitly rather than depending on each server’s php.ini:

<?php
// Session cookie settings, before session_start()
session_set_cookie_params( [
    'lifetime' => 0,              // until the browser is closed
    'path'     => '/',
    'domain'   => '',             // empty = exact host; '.example.com' = include subdomains
    'secure'   => true,           // HTTPS only: over HTTP the cookie isn't sent back
    'httponly' => true,           // not readable from JavaScript
    'samesite' => 'Lax',          // 'None' requires secure => true
] );
ini_set( 'session.use_strict_mode', '1' ); // reject made-up session IDs
session_start();

use_strict_mode has nothing to do with lost sessions, but it stops an attacker forcing a known ID on a victim (session fixation). Together with session_regenerate_id(true) at login, it’s the baseline for a properly secured session.

Server causes: storage, lifetime and multiple servers

If the ID is stable but the data vanishes, storage is the problem:

  • Directory not writable. After a migration or a change of PHP user, session.save_path sometimes points to a directory PHP can’t write to. The diagnostic script shows it, and the error log has an explicit warning.
  • Lifetime too short. session.gc_maxlifetime (1,440 seconds by default, i.e. 24 minutes) sets the age beyond which an idle session may be deleted. Raise it if your users fill in long forms.
  • Cleanup ignoring your setting. On some Linux distributions, it’s not PHP that purges sessions but a system scheduled task reading the global config. If several apps share the same directory with different lifetimes, the shortest wins. Give each app its own save_path.
  • Several servers behind a load balancer. Each server stores its files locally: if the next request lands on a different server, the session doesn’t exist there. It’s the classic app that “loses the session every other time” after scaling out.

For that last case, the clean fix is shared storage. Redis is what we pick most often: fast, with native key expiry.

; php.ini (or PHP-FPM pool): sessions shared across servers via Redis
; requires the phpredis extension
session.save_handler = redis
session.save_path    = "tcp://10.0.0.5:6379?prefix=sess_"
session.gc_maxlifetime = 7200

Sticky sessions on the load balancer help, but the session is lost as soon as a server restarts, during a deployment for instance.

A note for WordPress sites: core doesn’t use PHP sessions, its login relies on its own cookies. A plugin calling session_start() can, however, prevent page caching and cause these very symptoms; it’s often the one to look at.

FAQ

Why does the session work locally but not in production?

The usual differences: HTTPS (secure cookie), the domain (www or not), a different save_path, or several servers in production. Run the diagnostic script in both environments and the gap shows up straight away.

Should sessions be stored in the database?

You can, with session_set_save_handler(), but you then handle locking and cleanup yourself. To share sessions across servers, Redis or Memcached are simpler and faster.

How do I keep a user logged in for weeks?

Not by stretching the session forever: use a separate “remember me” token, stored hashed in the database, single-use and revocable, which recreates a session on the next visit.

Users logged out for no reason, a PHP application to harden before scaling up? We diagnose and fix the code and infrastructure behind your web and SaaS applications.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →