Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

PHP $_SESSION values are empty on the next page

Error$_SESSION is empty on the second page

Short answer

A session works only when the browser sends back the session cookie and session_start() runs before any output. Check what the response sets, then look at four causes: output before session_start, a missing call on a page, a Secure-only cookie over HTTP, and an iframe or domain that blocks the cookie.

  • Applies to PHP 8.3, PHP 8.4, Apache 2.4, PHP-FPM
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Look at the response headers of the first page and the request headers of the second. You want a Set-Cookie for PHPSESSID on the first and a Cookie header returning it on the second.

    curl -s -D - -o /dev/null -c jar.txt http://localhost/login.php
    curl -s -D - -o /dev/null -b jar.txt http://localhost/profile.php
  2. 2Match what you see, then jump to its fix

    1. 1The response has no Set-Cookie for PHPSESSID, and PHP warns about headersOutput is sent before session_start()Fix
    2. 2The login page sets values but another page sees an empty arrayA page reads $_SESSION without starting the sessionFix
    3. 3Set-Cookie is sent every time and the browser never sends it back, usually on a local or staging HTTP URLThe session cookie is Secure-only but the site runs on HTTPFix
    4. 4Works when opened directly, empty when embedded from another site, or only under one pathThe page is in an iframe or the cookie path and domain do not matchFix

What does the error look like?

  • $_SESSION is empty on the second page
  • session_start() has no effect and no cookie is sent
  • The session works on the site but not when the page is embedded in an iframe

Cause 1 of 4

Output is sent before session_start()

1Check

The manual says cookie-based sessions need session_start() called before anything is output, because it sends headers. A space before the opening tag, a BOM or an echo above it breaks that.

php -l login.php
head -c 20 login.php | xxd | head -n 2

2Fix

Move session_start() to the very top of the script, before any HTML or echo, and delete blank text before the opening php tag.

<?php
session_start();
$_SESSION['user_id'] = 42;

3Verify

The first curl from the first step now shows a Set-Cookie header with PHPSESSID.

curl -s -D - -o /dev/null http://localhost/login.php | grep -i set-cookie

Confirmed by php.net

Did this fix it?

Cause 2 of 4

A page reads $_SESSION without starting the session

1Check

Each request must call session_start() to resume the session. If a shared include or a framework hook calls it conditionally, some pages skip it. session_status() tells you the state at that point.

var_dump(session_status() === PHP_SESSION_ACTIVE);

2Fix

Start the session in one bootstrap file that every page includes, and guard it so a second call does not raise a notice.

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

3Verify

Set a value on page one and print it on page two.

echo $_SESSION['user_id'] ?? 'missing';

Confirmed by php.net

Did this fix it?

Cause 3 of 4

The session cookie is Secure-only but the site runs on HTTP

1Check

With session.cookie_secure on, the manual says sessions only work over HTTPS. Browsers also refuse to store a Secure cookie that arrives over plain HTTP, except on localhost.

php -r 'echo ini_get("session.cookie_secure"), "\n";'

2Fix

Serve the site over HTTPS, or turn the flag off in non-production environments only.

; php.ini or a staging override
session.cookie_secure = 0

3Verify

The second curl request now carries the cookie, and the page shows the stored value.

curl -s -b jar.txt http://localhost/profile.php

Confirmed by php.net

Did this fix it?

Cause 4 of 4

The page is in an iframe or the cookie path and domain do not match

1Check

Embedded in a page from a different site, the cookie counts as cross-site and the browser withholds it unless it is SameSite=None; Secure. Separately, session.cookie_path (default /) and session.cookie_domain set where the cookie is sent.

php -r 'print_r(session_get_cookie_params());'

2Fix

For a cross-site embed, set SameSite to None together with Secure, on HTTPS. Keep path as / and leave the domain empty unless subdomains must share a session.

session_set_cookie_params([
    'path'     => '/',
    'secure'   => true,
    'samesite' => 'None',
]);
session_start();

3Verify

Open the embedding page and check in the browser's network tab that the cookie is sent with the iframe request.

curl -s -D - -o /dev/null https://example.com/login.php | grep -i set-cookie

Confirmed by developer.mozilla.org

Did this fix it?

How do I stop it coming back?

  • Call session_start() in one bootstrap file at the top of every request, before output.
  • Use the same scheme (HTTPS) in every environment so cookie flags behave the same.
  • Set cookie parameters once, before session_start(), and nowhere else.
  • Treat embedding in an iframe as a cross-site case and test it in a real browser.

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

Users are logged out of a PHP session after a short idle time

$_SESSION is empty on the next request although the browser still sends the session cookie

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.

3 causes, each with a fix

Back 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 fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.