Solution to php setcookie failure: 1. Turn on cookies in the browser; 2. Delete any HTTP header output before setcookie(); 3. Use php's setcookie() to create a cookie.
The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer
php setcookie function invalid?
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. Obviously, the setting was unsuccessful. According to Google , it may be found that setcookie fails due to the following reasons:
The browser has disabled cookies. No need to check, I'm sure it's not disabled.
Using php's setcookie() to create cookies is the same as session_start() that opens the session in php. There cannot be any HTTP header output before setcookie(). I checked the code and found the following code
<p>var_dump($qOpenId);<br/>setcookie('qOpenId',$openid,time() + 30 * 24 * 3600,'/');<br/></p>
I commented decisively on the var_dump($OpenId) line, and the test was successful.
Personally think that setcookie should directly set the content in the http header, so there cannot be any header output in front, var_dump, echo, etc.
Recommended study: " PHP video tutorial》
The above is the detailed content of What to do if php setcookie fails. For more information, please follow other related articles on the PHP Chinese website!