I set a cookie but cannot retrieve it

This may be another stupid question, it bugged me a long time ago. I have not seen anyone mentioning this anywhere, perhaps it’s too obviously, but I think it’s worth to mention, especially for a newbie.

When you set a cookie in PHP, you cannot retrieve it right away, for example,

setcookie("user", "John Doe", time()+3600);
if (isset($_COOKIE["user"]))
  echo "Welcome " . $_COOKIE["user"] . "!
"; else echo "Welcome guest!

When you run this code in your browser at the first time, you will see “Welcome guest!”. You may think that we already set cookie before checking cookie, and cookie should be ready. But note that cookie is something saved in user’s computer, setcookie() function just sends the command, but cookie will not be created until the page loaded. So you can only retrieve the cookie in next PHP process (or the second page load.)

Easy? Good just skip this. Hopefully, I will bring some hard questions next time.

Leave a Reply

Your email address will not be published. Required fields are marked *