php setcookie not working

I set a cookie as follows:

setcookie(“mycookie”, “1”, time()+8);

The cookie “mycookie” is set to “1” and will expire in 8 seconds. The http Set-Cookie header received from the server is as follows:

Set-Cookie:mycookie=1; expires=Thu, 05-Apr-2018 18:34:17 GMT\r\n

As soon as I got the page, I issued the next request. Unfortunately, no http Cookie header was found in the http request. Why the php setcookie did not work as expected? In this case, the cookie is set to expire in short time. However, the specified expire time will be compared with the local time of the computer on which the browser is running, not the server time. If the local time is not synchronized to the server time, the short period expiration may confuse the browser. The inaccurate server/local computer clock made the browser think the cookie had already expired, so do not send the Cookie header. If you set a longer live time for the cookie, the problem will disappear, and you will findĀ  the Cookie header like:

Cookie: mycookie=1\r\n

php realizes the short cookie expiration time problem. If you delete a cookie as follows:

setcookie(“mycookie”, “”, time()-8);

php will not set the cookie’s expiration time to 8 second ago, but set to 1/1/1970 as follows:

Set-Cookie: mycookie=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT\r\n

So it is unlikely for the browser to consider the cookie as unexpired. Note that php also sets the value of the cookie to “deleted”, not “”. Browser uses the “expires” value instead of the value of the cookie to determine whether the cookie has expired or not. Note also that as long as you set a past expiration time, even 1 second ago, the sameĀ  Set-Cookie will be sent to the client. The current server time is enough for php to determine that the cookie is intended to be deleted.

 

Posted in

Comments are closed, but trackbacks and pingbacks are open.