How Do You Update A Cookie In Php?

If I call setcookie() two times with the same cookie name, I get two cookies created.

Bạn đang xem: How do you update a cookie in php?

How bởi you update an existing cookie?


*

*

You can update a cookie value using setcookie() function, but you should địa chỉ "/" in the 4th argument which is the "path" argument, khổng lồ prevent creating another cookie with the same name.

i.e. setcookie("cookie_name", "cookie_value", time()+3600, "/");

A suggested expiration time for the 3rd argument:

$exp_time = time()+3600; /* expire in 1 hour */$exp_time = time()+86400; /* expire in 1 day */
*

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 khổng lồ read "Common Pitfalls" from that page.

You can use the super global $_COOKIE<"cookie_name"> as well khổng lồ read cookies.


*

*

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

Xem thêm: Làm Sao Để Biết Ung Thư Di Căn Xương ? Ung Thư Di Căn Xương Là Gì

There should be a line lượt thích below in php vps 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
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 & name will overwrite each other, with the latest instance taking precedence. Instances of the same path but different names will địa chỉ additional mappings.

However, it might be advisable lớn avoid such edge conditions. Restructure your application so it doesn"t need lớn override the already sent cookie.


Thanks for contributing an answer to Stack Overflow!

Please be sure to lớn answer the question. Provide details và share your research!

But avoid

Asking for help, clarification, or responding khổng lồ other answers.Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.


Post Your Answer Discard

By clicking “Post Your Answer”, you agree lớn our terms of service, privacy policy và cookie policy


Not the answer you're looking for? Browse other questions tagged php cookies httpcookie cakephp or ask your own question.


Site design / logo sản phẩm © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. Rev2022.4.8.41922


Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device & disclose information in accordance with our Cookie Policy.