为何在PHP中的cookie值读取失败?

在同一网站下,使用 setcookie("userLogin","TEST",time()+60*60*24); 语句设置了cookie值,在本页面能用echo $_COOKIE["userLogin"]; 读取,但转到同一网站的其他页面用echo $_COOKIE["userLogin"]; 就读取不了,是空值。请问是哪里出问题了?

答案:

如果你在子目录的文件中 setcookie 的话,那么只能在该子目录的程序中看到设置的 cookie 变量
鉴于网站文件数较多,不大可能都放在根目录中,所以应令 setcookie 的第 4 个参数为 /,即使cookie 在整个网站中都有效。

参考:

path

The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.

 

使用setcookie另需注意的是:在设置 setcookie 之前如果存在任何输出的,将会令setcookie失效,此种情况,可以在输出前面使用 ob_start()函数。

参考:If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值