How do you update a cookie in PHP?

馋奶兔 提交于 2019-11-30 08:04:10
Francisc

You can't update a cookie per se, you can however overwrite it. Otherwise, this is what you are looking for: http://php.net/manual/en/function.setcookie.php

It works. Be sure to read "Common Pitfalls" from that page.

You can use the super global $_COOKIE['cookie_name'] as well to read/write cookies.

You can update a cookie value using setcookie() function, but you should add '/' in the 4th argument which is the 'path' argument, to prevent creating another cookie with the same name.

i.e. setcookie('cookie_name', 'cookie_value', $exp_date, '/');

So while PHP will send two Set-Cookie: headers if instructed so, only the last one should persist in browsers.
The Netscape cookie spec http://curl.haxx.se/rfc/cookie_spec.html says:

Instances of the same path and name will overwrite each other, with the latest instance taking precedence. Instances of the same path but different names will add additional mappings.

However, it might be advisable to avoid such edge conditions. Restructure your application so it doesn't need to override the already sent cookie.

Make sure there is no echo before setcookie call. setcookie communicates with browser through header, and if you called echo earlier, header+body is sent already and server cannot send setcookie to browser via header anymore. That is why you might see it is not working.

There should be a line like below in php server log file reporting warning in this case:

DEFAULT: PHP Warning:  Cannot modify header information - headers already sent by (output started at /path/to/your/script.php:YY) in /path/to/your/script.php on line XX

call COOKIE and delete username value SETCOOKIE("username",'',0,"/");

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!