1

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.

Mike
  • 37
  • 1
  • 4
  • can you write exact script you made and it's not working? – Mihai Iorga Aug 21 '12 at 14:12
  • 1
    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 Aug 21 '12 at 14:13
  • 1
    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. Aug 21 '12 at 14:14

1 Answers1

11

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.

Leri
  • 12,367
  • 7
  • 43
  • 60
  • Yes, I have set it as your suggested and this cookie have been displayed in firebug, but once it jumped to other page this cookie disappeared somehow. – Mike Aug 21 '12 at 14:21
  • 3
    Try setcookie('cookieusername', $username, time() + 100000, '/');, it should enable the cookie on your whole domain. – MarkR Aug 21 '12 at 14:24
  • 1
    Personally I wouldn't put the user name in the cookie at all. I would put a hash in that can be searched for in the database, which will give you your username. – Thomas Williams Feb 27 '17 at 11:42