Search code examples
phpcookiessetcookiehttpcookie

Not able to clear cookie what ever I do using PHP


I have tried a few ways to clear my cookies on localhost. Whatever I do, I am unable to delete them in Chrome and Firefox in normal mode, but it is working fine in Chrome's Incognito and Firefox's Private Browsing modes.

Here is my code:

$name = 'keepsignin';

if (isset($_SERVER['HTTP_COOKIE'])){
   $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
   foreach ($cookies as $cookie_id => $cookie_value){
       if($cookie_id === $name){
          self::set_cookie($cookie_id, $value, $expiry, $path, $domain);
       }
   }
}

After clearing the cookie manually things work fine, but I am not able to delete cookies that already exist.


Solution

  • $_SERVER['HTTP_COOKIE'] is a semi-colon delimited list of key-value pairs in the form:

    key1=value1;key2=value2;key3=value3;...
    

    You split the string at the ;, but not the =

    I think you might be looking for something like:

    $name = 'keepsignin';
    
    if (isset($_SERVER['HTTP_COOKIE'])) {
       $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
       foreach ($cookies as $cookie) {
           list($cookie_id, $cookie_value) = explode('=', $cookie);
           if($cookie_id === $name){
              self::set_cookie($cookie_id, $value, $expiry, $path, $domain);
           }
       }
    }
    

    Note the use of list() to assign $cookie_id and $cookie_value in one operation.