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

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

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?

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!