pindol
pindol

Reputation: 2110

php cookie doesn't update

I need to update a cookie. I do that in a php file called via ajax. This is is the code:

setcookie('items['.$_POST['id'].']');

The cookie does not update, in fact if I write print_r($_COOKIE['items']) after the setcookie function I see that $_COOKIE['items'] is the same that was before the call to setcookie function. How can I do?

Upvotes: 3

Views: 8738

Answers (5)

Mob
Mob

Reputation: 11106

You cannot set and access a cookie in the same instance/page. You have to do a redirect or refresh after setting it.

In addition, you should do something like this instead :

setcookie("id","items['.{$_POST['id']}.']");

Upvotes: 5

Rupesh Pawar
Rupesh Pawar

Reputation: 1917

This is syntax for setting a cookie

setcookie(name, value, expire, path, domain);

When you create a cookie, using the function setcookie, you must specify three arguments. These arguments are setcookie(name, value, expiration):

  1. name: The name of your cookie. You will use this name to later retrieve your cookie, so don't forget it!
  2. value: The value that is stored in your cookie. Common values are username(string) and last visit(date).
  3. expiration: The date when the cookie will expire and be deleted. If you do not set this expiration date, then it will be treated as a session cookie and be removed when the browser is restarted.

Note:- This will rewrite your cookie not update.

Upvotes: 1

steveo225
steveo225

Reputation: 11892

When you use setcookie is doesn't add the cookie to the superglobal $_COOKIE. You will have to do that yourself or reload the page. Also, since you are setting the cookie with an empty value, nothing would be set.

Upvotes: 2

ComFreek
ComFreek

Reputation: 29434

From php.net/manual/function.setcookie.php:

Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

So the cookie will be accessible via $_COOKIE at the request of the PHP script.

Upvotes: 0

matino
matino

Reputation: 17735

You have to set the value for the key to access with $_COOKIE:

setcookie('items['.$_POST['id'].']', 'some_value');

Link to manual

Upvotes: 1

Related Questions