note 130222 added to function.session-start

From: Date: Fri, 04 Apr 2025 01:15:07 +0000
Subject: note 130222 added to function.session-start
Groups: php.notes 
Request: Send a blank email to php-notes+get-222058@lists.php.net to get a copy of this message
Sessions are blocking by default - i.e. after calling session_start() the session file will be locked for reading until you either close that connection or explicitly call session_write_close(). That means any additional requests from that user (e.g. opening a new tab or XHR requests) which also open the session will have to wait for the previous request to finish - or at least wait for you to close the session. You can get around this by closing the session immediately after opening it (which lets you read session data), and then opening it again temporarily whenever you want to update the session: <?php // Passing an empty string here explicitly disables automatic cookie headers being generated session_cache_limiter(''); // You can then set your own session cookie header - and it's the ONLY session cookie header that will be included in the response setcookie(session_name(), session_id(), /* any other options you want */); // Note: I avoid using session_start(['read_and_close' => true]); because that doesn't update the last-modified date on the session file, which can result in sessions expiring even when they're being actively used. session_start(); session_write_close(); // ... some processing here session_start(); $_SESSION['myData'] = 'my value'; session_write_close(); ?> Note that the call to session_cache_limiter('') is important to avoid multiple set-cookie headers from being included in the response as others have noted. You then MUST set the cookie yourself, or it won't be set at all. Take a careful look at all the session cookie related options for session_start() and in php.ini to make sure you respect those options appropriately when setting your own cookies. ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.137 (proxied: 14.1.35.58) ---- Manual Page -- https://php.net/manual/en/function.session-start.php Edit -- https://main.php.net/note/edit/130222 Del: integrated -- https://main.php.net/note/delete/130222/integrated Del: useless -- https://main.php.net/note/delete/130222/useless Del: bad code -- https://main.php.net/note/delete/130222/bad+code Del: spam -- https://main.php.net/note/delete/130222/spam Del: non-english -- https://main.php.net/note/delete/130222/non-english Del: in docs -- https://main.php.net/note/delete/130222/in+docs Del: other reasons-- https://main.php.net/note/delete/130222 Reject -- https://main.php.net/note/reject/130222 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#222058) next »