为什么我的 cookie 没有设置?

Why are my cookies not setting?(为什么我的 cookie 没有设置?)
本文介绍了为什么我的 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 没有设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)