dongwei4103 2019-03-04 00: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 02: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'] : '';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部