問(wèn)題描述
我有以下 PHP 函數(shù):
I have the following PHP function:
function validateUser($username){
session_regenerate_id ();
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
setcookie('username2',$username,time()+60*60*24*365);
header("Location: ../new.php");
}
然后我獲取cookie:
And then I fetch the cookie:
echo $_COOKIE['username2'];exit();
(我只把 exit()
用于調(diào)試目的)
(I only put exit()
for debugging purposes)
唯一的問(wèn)題,它出來(lái)是空白的.有什么想法嗎?
Only problem, it's coming out blank. Any ideas?
更新:函數(shù)是這樣調(diào)用的:
if(mysql_num_rows($queryreg) != 0){
$row = mysql_fetch_array($queryreg,MYSQL_ASSOC);
$hash = hash('sha256', $row['salt'] . hash('sha256', $password));
if($hash == $row['password']) {
if($row['confirm'] == 1){
if(isset($remember)){
setcookie('username',$username,time()+60*60*24*365);
setcookie('password',$password,time()+60*60*24*365);
} else {
setcookie('username','',time()-3600);
setcookie('password','',time()-3600);
}
validateUser($username);
為了節(jié)省空間,我沒(méi)有包含所有的 if()
語(yǔ)句.
I didn't include all the if()
statements to save some space.
推薦答案
嘗試添加路徑 =/,這樣 cookie 就適用于整個(gè)站點(diǎn),而不僅僅是當(dāng)前目錄(之前已經(jīng)引起我注意)
try adding the path = /, so that the cookie works for the whole site not just the current directory (that has caught me out before)
示例
setcookie('password',$password,time()+60*60*24*365, '/');
還要確保 cookie 是第一個(gè)被輸出的東西正如 php 手冊(cè)中所建議的那樣(這也讓我感到困惑)
also make sure the cookie is the first thing being output as advised in the php manual (this has caught me out before too)
像其他標(biāo)頭一樣,cookie 必須在您的任何輸出之前發(fā)送腳本(這是一個(gè)協(xié)議限制).
Like other headers, cookies must be sent before any output from your script (this is a protocol restriction).
這篇關(guān)于為什么我的 cookie 沒(méi)有設(shè)置?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!