If I call setcookie()
two times with the same cookie name, I get two cookies created.
How do you update an existing cookie?
To update a cookie, simply overwrite its value in the cookie object. You do this by setting a new cookie on the document with the same Name, but a different Value.
The setcookie() function defines a cookie to be sent along with the rest of the HTTP headers. A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too.
Cookies are text files stored on the client computer and they are kept of use tracking purpose. PHP transparently supports HTTP cookies. Server script sends a set of cookies to the browser. For example name, age, or identification number etc.
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', time()+3600, '/');
A suggested expiration time for the 3rd argument:
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 cookies.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With