Home  >  Article  >  Backend Development  >  An old PHP bug: Duplicate Set-Cookie header received?

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

藏色散人
藏色散人forward
2022-10-18 16:53:474701browse

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 头

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  ,依然可以对文件进行 写操作

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

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!

Statement:
This article is reproduced at:yurunsoft.com. If there is any infringement, please contact admin@php.cn delete