phpsetcookieissetbrave

PHP Cookie doesn't exist even before actually deleting it in Brave


First I am setting a new cookie with PHP and checking whether it exists or not. After that I am deleting it by setting the expiry date to the past and checking again whether it was successful or not. What's odd is that when checking for existence for the first time the cookie already has been deleted even tho setting the expiry date comes AFTER.

<?php

setcookie("Test", "test", time() + 3600, "/", "", true, true);
if (isset($_COOKIE["Test"]))
{
  echo "<p>Cookie 'Test' exists.</p>";
} else {
  echo "<p>Cookie 'Test' doesn't exist.</p>";
}
setcookie("Test", "", time() - 3600);
if (isset($_COOKIE["Test"]))
{
  echo "<p>Cookie 'Test' exists.</p>";
} else {
  echo "<p>Cookie 'Test' doesn't exist.</p>";
}

?>

I expected the output in the Browser to be:

Cookie 'Test' exists.
Cookie 'Test' doesn't exist.


Solution

  • When you use setcookie, the cookie will be set on user's browser when they receive the page. so you cannot get the value of cookies in the same page.

    You cansend cookie and refresh the page then try to get cookies. (Because you cant send header and setCookie after writing to output)

    <?php
    
    if (!isset($_COOKIE["Test"]))
    {
      setcookie("Test", "test", time() + 3600, "/", "", true, true);
      header('location: /this_page.php');
      die;
    } else {
      echo "<p>Cookie 'Test' exists.</p>";
    }
    
    ?>
    

    or set cookies manually which is not recommended!

    <?php
    
    if(!isset($_COOKIE["Test"]))
    {
      setcookie("Test", "test", time() + 3600, "/", "", true, true);
      $_COOKIE["Test"] = "test";
    } else {
      echo "<p>Cookie 'Test' exists.</p>";
    }
    
    ?>