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 :

$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.


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: 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.

Follow us on Facebook and Twitter for latest update.