php讀取不了cookie
做一個登入介面,自動記憶使用者名稱的功能
if(empty($_POST['chkRemember'])) {
//使用者沒有選擇單選框
if(!empty($_COOKIE['username'])){
setcookie('username','',time()-100);
}
}else{
//使用者選擇單選框
setcookie('username',$username,time()+7*24*3600);
}
當使用者選了記住使用者名稱的單選框時,COOKIE已經儲存,在C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\Cookies菜單下多了一個COOKIE檔案(administrator@localhost[1].txt),內容也是正確的
但是讀取COOKIE卻不成功,每次都是返回控制
function GetCookieVal($key){
if(empty($_COOKIE[$key])){
return "none";
}else{
return $_COOKIE[$key];
}
}
?>
直接列印COOKIE數組 print_r($_COOKIE);
得到的也是空數組
求教這是怎麼回事?
是不是COOKIE儲存路徑和讀取路徑不一致?
分享到:
------解決方案--------------------
1、
setcookie('username',$username,time()+7*24*3600);
和
GetCookieVal("username")
必須是在不同的 HTTP 會話中進行的
2、你在設定 cookie 時 沒有指定路徑
所以 cookie 只在執行 setcookie 的程式所在路徑下有效
如果執行 GetCookieVal 的程式不在同一路徑下,則不會取到值
setcookie('username',$username,time()+7*24*3600,
'/');
這樣才可以使 cookie 變數 username 在整個網站中有效