为什么我的 cookie 没有设置? [英] Why are my cookies not setting?

查看:50
本文介绍了为什么我的 cookie 没有设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 PHP 函数:

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() 用于调试目的)

(I only put exit() for debugging purposes)

唯一的问题,它出来是空白的.有什么想法吗?

Only problem, it's coming out blank. Any ideas?

更新:函数是这样调用的:

    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);

为了节省空间,我没有包含所有的 if() 语句.

I didn't include all the if() statements to save some space.

推荐答案

尝试添加路径 =/,这样 cookie 就适用于整个站点,而不仅仅是当前目录(之前已经引起我注意)

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 是第一个被输出的东西正如 php 手册中所建议的那样(这也让我感到困惑)

also make sure the cookie is the first thing being output as advised in the php manual (this has caught me out before too)

像其他标头一样,cookie 必须在您的任何输出之前发送脚本(这是一个协议限制).

Like other headers, cookies must be sent before any output from your script (this is a protocol restriction).

这篇关于为什么我的 cookie 没有设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆