Search code examples
phpcookiesauthenticationsetcookie

Cookie is not being set in a browser [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.


Solution

  • 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'] : '';