Why do I get an undefined index when using cookies in PHP?

If I use the following base 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]; 

script dies during printing with an undefined index error. What am I doing wrong?

+4
source share
1 answer

Your lines:

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

What happens here is that you are setting a cookie, which means that the string * is added to the headers ready to be sent with your content.

think of it as a queue, and the queue goes to the browser only when you submit your content.

since your cookie is still in the queue, it was not actually set until the page was sent and you didn’t remember the page, and then, when you call, the browser will send the cookie information back to the browser, which, in turn, compiles the $_COOKIE array.

Think of it this way:

  • SetCookie ();
    • (ADDED TO CART)
  • try $_COOKIE
    • (NOT FOUND)
  • send content
    • (BROWSER SETS COOKIE TO FILE)
  • updates
    • (BROWSER SENDS COOKIE INFO SERVER)
  • php compiles
    • ($ _ COOKIE LOADED FROM BROWSER DATA)
  • try $_COOKIE
    • (found)

Hope this helps.

+22
source

Source: https://habr.com/ru/post/1336070/


All Articles