w3resource

Delete a given PHP cookie


3. Delete "username" Cookie

Write a PHP script to delete a cookie named "username".

Sample Solution:

PHP Code :

<?php
$cookieName = "username";

// Set the cookie expiration time to the past to delete the cookie
setcookie($cookieName, "", time() - 3600);

echo "Cookie named 'username' has been deleted.";
?>

Sample Output:

Cookie named 'username' has been deleted.

Explanation:

In the above exercise -

  • The variable $cookieName contains the cookie name we want to delete, "username".
  • To delete the cookie, we use the setcookie() function with the same cookie name, an empty value, and a past expiration time (specifically, one hour ago). Setting the expiration time to the past causes the cookie to be immediately expired and removed from the browser.
  • After deleting the cookie, we display a message indicating that the cookie named "username" has been deleted.

Flowchart:

Flowchart: Delete a given PHP cookie.

For more Practice: Solve these Related Problems:

  • Write a PHP script to delete the cookie "username" by setting its expiration time in the past and verify its removal.
  • Write a PHP function to remove a cookie named "username" and then redirect the user to a confirmation page.
  • Write a PHP program to unset the "username" cookie and log the deletion event to a file.
  • Write a PHP script to check if the "username" cookie has been deleted and display an appropriate message.

Go to:


PREV : Delete "username" Cookie.
NEXT : Set "userid" Session Variable.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.