Search code examples
phpcookiessetcookie

Initial creating then deleting a cookie works, but can't recreate it afterwards


I need to create and delete cookies.

The issue is that I can create, then delete cookie, but after previously deleted cookie I am not able to create a new one. Why?

It works once more after I clear the cache of the browser.

Creating cookie and redirecting to test page:

<?php
    $cookie_name = 'name';
    $cookie_time = 2000000000;
    $cookie_path = '/';
    $cookie_value = uniqid();

    setcookie($cookie_name, $cookie_value, $cookie_time, $cookie_path);

    echo '<script> window.location.assign("test.php"); </script>';
?>

Deleting a cookie and redirecting to test page:

<?php
    $cookie_name = 'name';
    $cookie_path = '/';

    setcookie($cookie_name, '', time() - 3600, $cookie_path);

    echo '<script> window.location.assign("test.php"); </script>';
?>

The test page just has print_r($_COOKIE); in it.

What am I doing wrong here? Is the name of the cookie an issue? Is it browsers limitation?

I need to be able to create and delete the cookie whenever I need to.

I tried to avoid the cache by using this code:

<?php
header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?> 

Solution

  • The problem may be the browser is caching the page request independently of what the server is telling it to do.

    There is a simple trick to get around this. Adding a changing variable to the query string will make the page request unique each time. This will also force the browser to re-load the page even when cached.

    For example, add the following to the address bar / page request:

    ?abc=123
    

    And change the number value each time. Alternatively you can even use a timestamp like so:

    ?<timestamp>
    

    This will force a standards compliant browser to fetch the page each time.