Skip to content
Advertisement

Cookies not set using PHP setcookie function

I’m using the setcookie php function to set some cookies in my browser. I try to set cookies in my php code and then I check it using print_r($_COOKIE). Cookies are not displayed, however if I try to set cookie in another file they will be displayed correctly.

if (isset($_POST['username']) && isset($_POST['password']))
{
    global $username,$password;
    $username = $_POST['username'];
    $password = sha1($_POST['password']);
    setcookie('username', $username, time()+3600); //cookie not set
    setcookie('password', $password, time()+3600); //cookie not set
    $database = connect_to_database($db_path);
    $result = $database->query("SELECT * FROM users WHERE username = '$username' AND password = '$password'");
    while (true)
    {
        $response = $result->fetchArray(SQLITE3_ASSOC);
        if (!$response)
        {
            unset($_COOKIE['username']);
            unset($_COOKIE['password']);
            break;
        }
        if (($response['username'] == $username) && $response['password'] == $password)
        {
            header("location: ../index.php");
        }
    }

}

I expected cookies to be set, but using print_r($_COOKIE); returns me array()

Notes

  • Cookies are allowd in my browser settings
  • $_POST['username'] & $_POST['password'] sent to this page via form in another page
  • $_POST['username'] & $_POST['password'] are set with true value.

Advertisement

Answer

Make sure you have a domain that is known by both server and client. echo $_SERVER['HTTP_HOST'] should tell you the exact same domain that your browser has. If not, cookie will not be accepted by the browser.

Make sure your server and client time is perfectly correct. Browser will reject a cookie with a wrong datetime.

Do not write any other code and just do:

<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day 
// expiration
echo date("H:i:s d.m.Y")."<br>";
echo $_SERVER['HTTP_HOST']."<br>";
var_dump($_COOKIE);
?>

and refresh the page twice.

Also check out manual at: https://www.php.net/manual/en/features.cookies.php

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement