Ame
Ame

Reputation: 163

Can't update cookie

I'm running into a strange problem, I can't update cookies. I'm perfectly able to read it and to set it (just the first time). Then every time I try to update it (for logout or update the cookie's info) nothing happens.

Basically when I login I use this code

$cookie_time = (3600 * 24 * 30); // 30 days
$cookietime = time() + $cookie_time;
$cookie_name = 'login';
$cookie_value = 'enter';    
setcookie ($cookie_name, 'id='.$selector.'&token='.$token, $cookietime);

and I can set it perfectly.

When I logout I use this code

$cookie_time = 1; // 1 days
$cookie_name = 'login';
$cookie_value = 'exit'; 
setcookie($cookie_name, $cookie_value, $cookie_time);

The cookie doesn't change at all. Even if I try to login again without logging out (I made this possible by code) the cookie doesn't change. Looks like it's impossible to update it... I made many attempts but I have no ideas how to solve it! Is it possible that my PHP doesn't allow to set cookies that are already set?

Upvotes: 0

Views: 619

Answers (2)

Dan
Dan

Reputation: 11084

From the setcookie docs.

Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.

Are you outputting anything before trying to update the cookie

Upvotes: 0

Cr3aHal0
Cr3aHal0

Reputation: 809

Be careful, $cookie_time should correspond to a timestamp relative to the 1 Jan 1970 and not only a time in ms.

see http://php.net/manual/fr/function.setcookie.php

$cookie_time should be :

$cookie_time = time() + (3600 * 24 * 30);

the time() function returns the actual timestamp and $cookie_time now represents a expire date in the future ;)

Upvotes: 2

Related Questions