在同一网站下,使用 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.