PHP - HTML Removing Cookies

Introduction

To delete a cookie, call setcookie() with the cookie name and any value, and pass in an expires argument that is in the past.

This immediately expires the cookie on the browser, ensuring that it is deleted.

You should pass exactly the same path, domain, and other fields that you used when you first created the cookie to ensure that the correct cookie is deleted:

setcookie("Size" ," " , time()-3600," /" ," .example.com" , false, true);

Here, this example sets the Size cookie's expiry time to one hour in the past, which effectively deletes it from the browser.

Deleting a cookie via setcookie() doesn't delete it from the $_COOKIE array while the script is running.

However, the next time the browser visits the page, it will no longer send the cookie to the server and the corresponding $_COOKIE array element will not be created.

Example

the following code shows how to use cookie to store and pass user information

<?php
if (isset($_POST[" sendInfo" ])) {
  storeInfo();
} elseif (isset($_GET[" action" ]) and $_GET[" action" ] =="forget" ) {
  forgetInfo();
} else {
  displayPage();
}

function storeInfo() {
  if (isset($_POST[" firstName" ])) {
    setcookie(" firstName" , $_POST[" firstName" ], time() + 60 * 60 * 24 * 365, " " ," " , false, true);
  }

  if (isset($_POST[" location" ])) {
  setcookie(" location" , $_POST[" location" ], time() + 60 * 60 * 24 * 365," " , " " , false, true);
  }
  header(" Location: remember_me.php" );
}

function forgetInfo() {
  setcookie(" firstName" ," " , time()-3600," " ," " , false, true);
  setcookie(" location" ," " , time()-3600," " ," " , false, true);
  header(" Location: remember_me.php" );
}

function displayPage() {
  $firstName = (isset($_COOKIE[" firstName" ])) ? $_COOKIE[" firstName" ] :" " ;
  $location = (isset($_COOKIE[" location" ])) ? $_COOKIE[" location" ] :" " ;

?>

<html>
   <head>
     <title> Remembering user information with cookies </title>
   </head>
<body>
Remembering user information with cookies

<?php if ($firstName or $location) { ?>
    Hi,  <?php echo $firstName ? $firstName :" visitor" ?>  
         <?php echo $location ?" in $location" :" " ?> ! </p>

     <a href="remember_me.php?action=forget"> Forget about me! </a>  </p>
<?php } else { ?>
     <form action="remember_me.php" method="post">
       <div style="width: 30em;">
         <label for="firstName"> What's your first name? </label>
         <input type="text" name="firstName" id="firstName" value="" />
         <label for="location"> Where do you live? </label>
         <input type="text" name="location" id="location" value="" />
         <div style="clear: both;">
           <input type="submit" name="sendInfo" value="Send Info" />
         </div>
       </div>
     </form>

<?php } ?>
<?php
}?>

   </body>
 </html>

Related Topic