Open In App

Remove a cookie using PHP

Cookie: A Cookie is a small file sent by the server to preserve stateful information for a user. It is stored on the client’s computer and sent to the server every time the user makes a request for the same page.

To create cookies you can set the cookie by using the setcookie() function of the PHP.



Syntax: 

setcookie(name, value, expire, path, domain, secure, httponly)

Parameters: This function accepts seven parameters as mentioned above and described below:  



Out of the above parameters, only the first two parameters are mandatory. Others are optional parameters. If you want to preserve the cookie, then provide the expire-time parameter.

Note: It is stored in the global array named $_COOKIE.

Creating a Cookie: As mentioned earlier, we can set cookies by using the function setcookie().  




<!DOCTYPE html>
  
<?php
$cookie_name = "gfg";
$cookie_value = "GeeksforGeeks";
  
// 86400 = 1 day
setcookie($cookie_name, $cookie_value, time() + (86400 * 15), "/"); 
?>
  
<html>
<body>
    <?php
    if(!isset($_COOKIE[$cookie_name])) {
          echo "Cookie named '" . $cookie_name . "' is not set!";
    
    else {
          echo "Cookie '" . $cookie_name . "' is set!<br>";
          echo "Value is: " . $_COOKIE[$cookie_name];
    }
    ?>
  
</body>
  
</html>

Cookie 'gfg' is set!
Value is: GeeksforGeeks

Deleting Cookie: There is no special dedicated function provided in PHP to delete a cookie. All we have to do is to update the expire-time value of the cookie by setting it to a past time using the setcookie() function. A very simple way of doing this is to deduct a few seconds from the current time. 

setcookie(name, time() - 3600);




<!DOCTYPE html>
<?php
  
// Set the expiration date to one hour ago
setcookie("gfg", "", time() - 3600);
?>
  
<html>
  
<body>
  
    <?php
    echo "Cookie 'gfg' is deleted.";
    ?>
  
</body>
  
</html>

Cookie 'gfg' is deleted.

Note: The setcookie() function must appear before the <html> tag.
 

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.


Article Tags :