Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get undefined index while using cookie in PHP?

Tags:

php

cookies

If I use the following basic code

if (!defined('NAME_COOKIE') )
 define('NAME_COOKIE', "storedusername");

$cookie_domain = ".".$_SERVER['HTTP_HOST'];

setcookie(NAME_COOKIE, $username,time() + (86400),"/", $cookie_domain);
print $_COOKIE[NAME_COOKIE];

The script dies during the print with undefined index error. What am I doing wrong?

like image 729
deltanovember Avatar asked Nov 30 '22 04:11

deltanovember


1 Answers

Your lines:

setcookie(NAME_COOKIE, $username,time() + (86400),"/", $cookie_domain);
print $_COOKIE[NAME_COOKIE];

Whats happening here is that your setting the cookie, which means that a string is *added to the headers, ready to send with your content.

think of this like a queue, and the queue goes to the browser only when you send your content.

as your cookie is still in the queue, its not actually been set until the page gets sent and you recall the page, then upon the recall the browser will send the cookie information back to the browser which in turn compiles the $_COOKIE array.

Try think of it like this:

  • setcookie();
    • (ADDED TO THE QUEUE)
  • try $_COOKIE
    • (NOT FOUND)
  • send content
    • (BROWSER SETS COOKIE TO FILE)
  • refresh
    • (BROWSER SENDS COOKIE INFO TO SERVER)
  • php compiles
    • ($_COOKIE LOADED FROM BROWSER DATA)
  • try $_COOKIE
    • (FOUND)

Hope this helps.

like image 177
RobertPitt Avatar answered Dec 14 '22 23:12

RobertPitt