此代码段无法正确设置Cookie的任何原因? [英] Any reason why this code snippet wouldn't set a cookie properly?
问题描述
这个小的PHP代码片段用于设置一个cookie,让我确定用户是否登录。出于某种原因,在我使用javascript重定向后,我的Cookie都不会被设置。为什么会发生这种情况的任何原因?
This little PHP snippet is used to set a cookie that lets me determine whether or not a user is logged in. For some reason, after I use the javascript to redirect, none of my cookies are set any more. Any reason why this would be happening?
我可能没有给您足够的信息,所以让我知道是否这样。
I may not be giving you enough info so let me know if so.
...some database queries...
<?php
$expire=time()+(7 * 24 * 60 * 60);
$row = mysql_fetch_array($query);
$email = $row['email'];
$userinfo['name'] = $name;
$userinfo['email'] = $email;
$userinfo = serialize($userinfo);
setcookie("user", $userinfo, $expire);
echo '<script type="text/javascript">
window.location = "../index.php";
</script>';
?>
推荐答案
函数setcookie返回true或false,设置成功。您可以尝试这个测试:
Function setcookie returns true or false, depending on whether cookie was set successfully. You could try this to test:
if(!setcookie("user", $userinfo, $expire)) {
echo 'Could not set cookie!';
}
如果这返回false,那么Kumar是正确的。否则必须有其他原因。
If this returns false, then Kumar is right. Otherwise there has to be some other reason.
EDIT setcookie可以使用更多参数调用,如下所示:
EDIT setcookie can be called with more parameters, like this:
setcookie(name,value,expire,path,domain,secure)
注意路径和域值。我有过问题,因为两个不同的页面,因为不同的路径/域而找不到对方的Cookie。
Notice the path and domain values. I have had problems in the past with two different pages not find each other's cookies because of different paths/domains.
我注意到你重定向到../index。 php。尝试重定向到index.php,并查看是否存在cookie。如果是,那么您应该使用一个公共的路径变量来设置Cookie。
I noticed that You redirect to "../index.php". Try redirecting to "index.php" and see if the cookies exist there. If yes, then You should use a common "path" variable to set cookies.
从 http://www.php.net/setcookie 关于路径变量:
服务器上将存在Cookie的路径。如果设置为/,则Cookie将在整个域中可用。如果设置为/ foo /,那么cookie只能在/ foo /目录和所有子目录(如/ foo / bar / of domain)中可用。默认值是设置Cookie的当前目录。
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.
这篇关于此代码段无法正确设置Cookie的任何原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!