Wednesday 5 December 2012

Unset all cookies in PHP

Delete / Unset all cookies in PHP

If you want to delete all cookies on your domain, you may want to use the value of:
<?php   $_SERVER['HTTP_COOKIE']   ? >
rather than:
<?php  $_COOKIE  ? >
to dertermine the cookie names. 

If cookie names are in Array notation, eg: user[username] 

Then PHP will automatically create a corresponding array in $_COOKIE. Instead use  $_SERVER['HTTP_COOKIE']  as it mirrors the actual HTTP Request header. 

So you can unset all cookies by the following way.

<?PHP
 
// Unset all cookies in PHP 
 
if (isset($_SERVER['HTTP_COOKIE'])) {  
 
        $cookies = explode(';', $_SERVER['HTTP_COOKIE']);  
         
        foreach($cookies as $cookie) {  
         
                $parts = explode('=', $cookie);
                 
                $name = trim($parts[0]);
                 
                setcookie($name, '', time()-1000);
                 
                setcookie($name, '', time()-1000, '/');
         
        }
 
}
 
?>
Reference : http://php.net/manual/en/function.setcookie.php
Hope this helps!


No comments:

Post a Comment