问题
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>';
?>
回答1:
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!';
}
If this returns false, then Kumar is right. Otherwise there has to be some other reason.
EDIT setcookie can be called with more parameters, like this:
setcookie(name,value,expire,path,domain,secure)
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.
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.
From http://www.php.net/setcookie about "path" variable:
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.
回答2:
Tory, make sure you do not output anything before you call set setcookie
in PHP. Not even white space. No echo. Nothing. What I guess is your scripts outputs some thing before setcookie and that breaks your script. Do you see header already sent error? Comment out your JS and then check. You setcookie in this way
setcookie(name,value,expire,path,domain,secure);
Domain needs a domain name value in string like example.com
, its optional. Secure needs a boolean value and is optional. Skip these two and check by setting path to '/'
回答3:
Probably because $userinfo is an array. It has to be a string, to store multiple items you need multiple cookies
来源:https://stackoverflow.com/questions/6942977/any-reason-why-this-code-snippet-wouldnt-set-a-cookie-properly