Resolving Duplicate Set-Cookie Header Caused by Repeated session_start() Calls in PHP
The article explains why calling PHP's session_start() multiple times generates duplicate Set-Cookie headers, provides a code-based fix using session_abort() and header_remove(), and discusses session file locking, cookie lifetime, and garbage collection settings to manage session behavior effectively.
During development a recurring bug was discovered where the front‑end received duplicate Set‑Cookie headers because the session_start() function was being invoked repeatedly.
Each call to session_start() outputs a Set‑Cookie header, leading to the duplication issue.
Solution:
<code>session_start();</code><code>session_abort();</code><code>header_remove('Set-Cookie'); // 移除 Set-Cookie 头</code>Extended explanation: After session_start() the associated session file is locked until the script ends, so any other process trying to access the same session ID must wait for the lock to be released before it can call session_start() again.
Additional details about session handling:
session.cookie_lifetime defaults to 0, meaning the cookie expires when the browser closes.
The session_set_cookie_params function can also set the cookie lifetime.
session.gc_maxlifetime defaults to 1440 seconds; if the interval between two requests exceeds this, the session file may be considered garbage and removed when gc_probability/gc_divisor equals 1.
Example configuration to set both the session cookie and the session file to expire after one day (86400 seconds):
<code>session.cookie_lifetime=86400</code><code>session.gc_maxlifetime=86400</code><code>session.gc_probability=1</code><code>session.gc_divisor=1</code>Further code demonstrating session usage and proper closing of the write lock:
<code>session_start(); // starts the session, exclusive lock on the session file</code><code>$_SESSION['user'] = "Me"; // write variable to the session file</code><code>session_write_close(); // close write capability, release lock</code><code>echo $_SESSION['user']; // still accessible after closing</code>php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.