views:

59

answers:

5

I'm just trying to set and use a cookie but I can't seem to store anything.

On login, I use:

setcookie("username", $user);

But, when I use Firefox and the Web Developer plugin Cookies -> View Cookie Information There is no username cookie.

Also, when I try to access the value from a subsequent page using

$_COOKIE["username"]

It is returning null/empty

var_dump(setcookie("username", $user)); RESULT: bool(true)

and

var_dump($_COOKIE) RESULT: specific cookie does not exist (others are there)

I have done some more testing...

The cookie exists after login (first page) but disappears when I go to another (2nd page) and is lost for good...

Are there any headers that must be present or not present?

+1  A: 

http://php.net/manual/en/function.setcookie.php

Try setting the $expire parameter to some point in the future. I believe it defaults to 0, which is in the distant past.

JCD
No. If set to zero, the cookie expires at the end of the browser session.
thomasrutter
Thanks thomasrutter - that's exactly how I understood it...
php-b-grader
A: 

The cookie is probably expired because $expire defaults to 0 seconds since the Unix epoch. (docs)

Try

setcookie("username", $user, time() + 1200);

which expires 20 minutes after set (based on the client's time).

dpoeschl
No. If $expire is set to zero, the cookie expires at the end of the browser session.
thomasrutter
A: 

Use var_dump() on setcookie(..) to see what is returned. Also might do the same to $_COOKIE to see if the key is set.

John Hoover
+1  A: 

Make sure that you are setting the domain parameter correctly in case the URL is changing after you go to another page after login. You can read more about the domain parameter on http://php.net/manual/en/function.setcookie.php

Aditya
The URL is definitely changing but the domain is not. The domain is definitely staying the same!
php-b-grader
A: 

Thanks everyone for the feedback... Aditya lead me to further analyse the cookie and I discovered that the path was the issue...

The login path was /admin/ and then I was redirecting back to the root...

Thanks all for your help and feedback!

php-b-grader