Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you update a cookie in PHP?

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

How do you update an existing cookie?

like image 489
Cookie Avatar asked Jun 26 '11 23:06

Cookie


People also ask

How do I update cookie data?

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.

Which PHP function is used to modify a cookie?

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.

How are cookies handled in PHP?

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.


3 Answers

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:

  • $exp_time = time()+3600; /* expire in 1 hour */
  • $exp_time = time()+86400; /* expire in 1 day */
like image 150
Omar Alahmed Avatar answered Oct 19 '22 00:10

Omar Alahmed


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.

like image 23
Francisc Avatar answered Oct 18 '22 23:10

Francisc


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
like image 6
lashgar Avatar answered Oct 18 '22 23:10

lashgar