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 请教一下simulink中S函数相关问题
    • ¥15 Hadoop中eclipse运行问题
    • ¥15 在二层网络中,掩码存在包含关系即可通信
    • ¥15 端口转发器解析失败不知道电脑设置了啥
    • ¥15 Latex算法流程图行号自定义
    • ¥15 关于#python#的问题:我在自己的电脑上运行起来总是报错,希望能给我一个详细的教程,(开发工具-github)
    • ¥40 基于51单片机实现球赛计分器功能
    • ¥15 cs2游戏画面卡住,应用程序sid与指挥者sid不匹配
    • ¥15 实验七:Pandas要有实验截图和代码
    • ¥15 TypeError: Make sure that the iterable only contains strings.