An old PHP bug: Duplicate Set-Cookie header received?

藏色散人
Release: 2023-04-11 08:18:01
forward
4864 people have browsed it

An old PHP bug: Duplicate Set-Cookie header received?

#How to solve the problem when PHP outputs duplicate Session Set-Cookie headers?

I encountered an old bug today that I had never discovered before. The front-end response received two duplicate Set-Cookie headers.

I was puzzled and after a long time of troubleshooting, I finally determined that it was caused by repeated calls to the session_start() function.

Every time the session_start() function is called, a Set-Cookie header will be output.

Solution:

session_start();
session_abort();
header_remove('Set-Cookie'); // 移除 Set-Cookie 头
Copy after login

Expansion:

The corresponding session file is locked after session_start() and will not be unlocked until the end of the current script .

During the lock period, if a process accesses the same session id, session_start() will not start until the file is unlocked.

session_start();                               //starts the session,独占对应session id的文件
$_SESSION['user']="Me";               将变量写入对应的session 文件
session_write_close();                   // close write capability   ,关闭对文件 的 写独占
echo $_SESSION['user'];              // you can still access it  ,依然可以对文件进行 写操作
Copy after login

session.cookie_lifetime defaults to 0, which means that the cookie becomes invalid when the browser is closed.

In addition to configuring cookie_lifetime in php.ini, it can also be set through the function session_set_cookie_params.

session.gc_maxlifetime The default is 1440 seconds, that is to say, if the time interval between two user requests exceeds 1440 seconds,

The server-side session file will be treated as garbage by PHP, if gc_probability/gc_divisor equals 1 , the session file will be deleted and recycled.

Set the session cookie and session file to expire after 86400 seconds (1 day):

session.cookie_lifetime=86400
session.gc_maxlifetime=86400
session.gc_probability=1
session.gc_divisor=1
Copy after login

Recommended learning: "PHP Video Tutorial

The above is the detailed content of An old PHP bug: Duplicate Set-Cookie header received?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yurunsoft.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template