1
votes

I'm new PHP guy and I'm using PHP cookie and I'm facing a problem that the cookie can not be set correctly. Here is the statement of Set Cookie

setcookie('cookieusername', $username, 100000);

and the statement of Get Cookie

$cookieusername = $_COOKIE["cookieusername"];

The problem is, the value of $_COOKIE["cookieusername"]; is not defined.

I don't know what the problem is. I have tired to set the cookie path to '/' but which was still not work.

1
can you write exact script you made and it's not working? - Mihai Iorga
Are you sure headers are not sent already ? var_dump(headers_sent()) to check. If not, cookies will be loaded on NEXT page visit (You cannot access a cookie you just set) - Touki
Your expiry time is set in past. 100000 is not for how long it should last, it's UNTIL when it should last, read up at php.net/setcookie - N.B.

1 Answers

11
votes

Instead of:

setcookie('cookieusername', $username, 100000);

you have to do:

setcookie('cookieusername', $username, time() + 100000);

The reason is that the third parameter is the expiry time (as a Unix timestamp (number of seconds since the epoch)), not the time until expiry. And here's the link of manual.