|   | php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login | 
| 
  [2019-10-03 11:45 UTC] james at gogo dot co dot nz
 Description: ------------ In PHP 7.2 (I believe) session_start() was modified with regard to it's abilities after headers had been sent. It was stated regarding the changes (https://externals.io/message/96387) that "it changes behavior only when there is useless session which is fatal anyway", this is not the case. In versions, at least in up to 5.6, if the browser sent OR if before output you explicitly and manually set the session_id() cookie then you could successfully and normally (save for notice/warning) session_start() after output and that $_SESSION would be perfectly functional and indeed get written back quite normally. I can not speak for others, but I routinely used this method successfully through the last decade in order to delay session starting as long as possible (if at all) to reduce lock contention. session_start() prior 7.2 allowed one to set just the cookie themselves prior output and start session successfully using that cookie after output, 7.2 forward does not. Test script: --------------- <?php if(!isset($_COOKIE[session_name()])) { session_id(uniqid('session-')); setcookie(session_name(), session_id(), 0, '/'); } header('Content-Type: text/plain'); echo "PHP Version: " . phpversion() . "\n"; echo str_repeat(' ', 1024); flush(); // ensure output is flushed echo "Headers Sent Before session_start(): " . (headers_sent() ? 'Y': 'N') . "\n"; @session_start(); echo "Incrementing session variable (should increment each reload): " . ($_SESSION['testvar'] ? $_SESSION['testvar'] : 0) . "\n"; $_SESSION['testvar'] += 1; ?> Expected result: ---------------- The value for "Incrementing session variable" should increase on each reload (PHP 5.6 below) Actual result: -------------- The value for "Incrementing session variable" remains 0 (PHP 7.2 above) PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits             | |||||||||||||||||||||||||||
|  Copyright © 2001-2025 The PHP Group All rights reserved. | Last updated: Fri Oct 31 11:00:01 2025 UTC | 
An obvious workaround presents itself. ---------- // BEFORE OUTPUT ini_set('session.use_cookies', 0); ini_set('session.cache_limiter', ''); if(!isset($_COOKIE[session_name()])) { session_id(uniqid('session-')); // don't use uniqid in real life! setcookie(session_name(), session_id(), 0, '/'); } else { session_id($_COOKIE[session_name()]); } // Then you can session_start() any time. // // Under the proviso that the cache_limiter is not set, but // that would not have been done previous to 7.1 anyway in this same // circumstance. // // You can (should) always set your own cache limiting headers anyway // by your own rules.