Home > Article > Backend Development > php setcookie function fails
Recently, when I was writing a php backend for a website, I found that the setcookie function could not always set cookies normally. Through var_dump(), I found that the return value of the function was false, which obviously means that the setting was unsuccessful. After searching Google, I found that the setcookie failure may be caused by something like this. Reason:
1. The browser has disabled cookies. No need to check, I'm sure it's not disabled.
2. Using php's setcookie() to create cookies is the same as session_start() to open a session in php. There cannot be any HTTP header output before setcookie(). I checked the code and found the following code
var_dump($qOpenId); setcookie('qOpenId',$openid,time() + 30 * 24 * 3600,'/');
decisively commented the line var_dump($OpenId), the test was successful.
Personally, I think that setcookie should directly set the content in the http header, so there can’t be any header output in front, var_dump, echo, etc.
Related articles:
Please tell me if setcookie does not set the expiration time. How to write the set path?
cookies settings PHP setcookie settings Cookie usage and invalid settings