dongwei4103 2019-03-04 08:23
浏览 68
已采纳

Cookie未在浏览器中设置[PHP]

I have some simple static login PHP logic and trying to save the username in a cookie. Unfortunately, it doesn't save anything and also returns no errors, so I'm not really sure what's wrong. Maybe you can spot something in the code I'm doing wrong.

$users = array('allan'=>'allanpass');

$username = $_POST["username"];
$enterpass = $_POST["password"];

if(isset($_POST["username"])) {
    if (array_key_exists($username, $users)) {
        $pass = $users["allanpass"];
        if($enterpass == $pass) {
            setcookie("heyhey", 'user2', time() + 60 * 60 * 24 * 7, '/');
            echo "Welcome back! <br />";
            echo '<a href="login.php?link=link1">Link1</a><br />';
            echo '<a href="login.php?link=link2">Link2</a><br />';
            echo '<a href="login.php?link=link3">Link3</a><br />';

        } else {
            echo "pass does not exist";
        }
    } else {
        array_push($users, $username);
        echo "hello new user <br />";
        echo '<a href="#">Link1</a><br />';
        echo '<a href="#">Link2</a><br />';
        echo '<a href="#">Link3</a><br />';
    }
} else {
    echo "Please fill in the form";
};

EDIT: I have no previous cookies saved. Everything is destroyed.

  • 写回答

1条回答 默认 最新

  • duanliushua5026 2019-03-04 10:16
    关注

    Thank you everyone for your inputs but the problem was something else. It was that I was setting a cookie after my headers were sent. Now that doesn't mean I had to set a cookie on the top of my file, but I had some comments and spaces on the top of my file and removing these got rid of headers sent error. If removing spaces doesn't fix headers error, try using ob_start() before setting your cookie and ob_end_flush(); after. But that is not the best practice.

    I also was getting a warning for undefined indexes where I had my variables defined. Checking if values are set before assigning them to the variables I use inside if statement also helped.

    $username = isset($_POST['username']) ? $_POST['username'] : '';
    $enterpass = isset($_POST['password']) ? $_POST['password'] : '';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵