w3resource

Delete a given PHP cookie

PHP Cookies and Sessions: Exercise-3 with Solution

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.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Retrieve and display PHP cookie value for a given user.
Next: Set a session variable with the given value.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/cookies-sessions/php-cookies-sessions-exercise-3.php