我正在本地开发一个使用cookie的网站。我有一个函数,它会生成一个随机的25个字符的字符串,并将其存储在数据库中,并设置为用户浏览器上的参考cookie。
我已经在互联网和这个网站上进行了搜索,但是没有找到解决我的问题的方法。
以下是相关代码的概述。
我已经在互联网和这个网站上进行了搜索,但是没有找到解决我的问题的方法。
以下是相关代码的概述。
function generateRandomString($length){
$string = "";
$possible = "012346789abcdefghijklmnopqrstuvwABCDEFGHIJKLMNOPQRSTUVW";
$maxlength = strlen($possible);
if($length > $maxlength){
$length = $maxlength;
}
$i = 0;
while($i < $length){
$char = substr($possible, mt_rand(0, $maxlength-1), 1);
if(!strstr($string, $char)){
$string .= $char;
$i++;
}
}
return $string;
}
$uCookie = generateRandomString(25);
setcookie('uHash', $uCookie, time()+60*60*24*30);
$stmt = $dbh->prepare('
UPDATE User
SET u_UserCookie = :cookie
WHERE u_UserId = :id
');
$stmt->execute(array(
':cookie' => $uCookie,
':id' => $user_id
));
现在当我尝试使用echo($_COOKIE['uHash']);
时,我得到一个空字符串。
奇怪的是,当我检查我的Chrome首选项时,cookie确实存在。
Name: uHash
Content: 134uHnEPrCmBNGqeAjhRSUiJL
Domain: localhost
Path: /~path/to/login
Send for: Any kind of connection
Accessible to script: Yes
Created: Wednesday, April 17, 2013 4:21:27 PM
Expires: Friday, May 17, 2013 4:21:27 PM
数据库中也可以找到字符串“134uHnEPrCmBNGqeAjhRSUiJL”,所以这是有效的。
我是否缺少有关本地主机上Cookie的基本信息?
已解决
问题在于,根据php.net的说法
“域名必须至少包含两个点(.),因此'localhost'是无效的,浏览器将拒绝设置Cookie”
所以我通过以下方式解决了这个问题
$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
setcookie('uHash', $uCookie, time()+60*60*24*30, '/', $domain, false);
$_COOKIE
的值,而该值是在该脚本中设置的? - Barmar