为什么在PHP中使用Cookie时会得到未定义的索引? [英] Why do I get undefined index while using cookie in PHP?

查看:63
本文介绍了为什么在PHP中使用Cookie时会得到未定义的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用以下基本代码

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?

推荐答案

您的行:

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

这里发生的事情是您设置了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.

,因为您的Cookie仍在队列中,直到发送页面并重新调用页面后才真正设置它,然后在调用时浏览器将发送cookie信息返回到浏览器,浏览器依次编译 $ _ COOKIE 数组。

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.

尝试这样想:


  • setcookie();

    • (已添加到队列中)


    • (未找到)


    • (浏览器将Cookie设置为文件)


    • (浏览器向服务器发送COOKIE信息)


    • (从浏览器数据中加载$ _COOKIE)


    • (FOUND)

    希望这会有所帮助。

    这篇关于为什么在PHP中使用Cookie时会得到未定义的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆