0
0
PhpHow-ToBeginner · 3 min read

How to Delete Cookie in PHP: Simple Guide with Examples

To delete a cookie in PHP, use the setcookie() function with the cookie name and set its expiration time to a past timestamp, like time() - 3600. This tells the browser to remove the cookie immediately.
📐

Syntax

The basic syntax to delete a cookie in PHP is:

  • setcookie(name, '', time() - 3600);

Here:

  • name is the cookie's name you want to delete.
  • '' sets the cookie value to an empty string.
  • time() - 3600 sets the expiration time to one hour ago, which deletes the cookie.
php
setcookie('cookie_name', '', time() - 3600);
💻

Example

This example shows how to set a cookie and then delete it by setting its expiration time in the past.

php
<?php
// Set a cookie named 'user' that expires in 1 hour
setcookie('user', 'John', time() + 3600);
echo "Cookie 'user' is set.<br>";

// Delete the cookie by setting expiration time in the past
setcookie('user', '', time() - 3600);
echo "Cookie 'user' is deleted.";
?>
Output
Cookie 'user' is set. Cookie 'user' is deleted.
⚠️

Common Pitfalls

Common mistakes when deleting cookies include:

  • Not matching the path and domain parameters used when the cookie was set. Cookies are identified by name, path, and domain.
  • Trying to delete a cookie after output has started without using output buffering, causing headers to fail.
  • Assuming deleting a cookie on the server removes it from the browser; you must send the deletion command to the browser.
php
<?php
// Wrong: Missing path, cookie may not delete if path differs
setcookie('user', '', time() - 3600);

// Correct: Match path and domain if originally set
setcookie('user', '', time() - 3600, '/');
?>
📊

Quick Reference

Tips for deleting cookies in PHP:

  • Always set the expiration time to a past timestamp.
  • Match the path and domain parameters exactly as when the cookie was created.
  • Call setcookie() before any output to avoid header errors.
  • Deleting a cookie means instructing the browser to remove it; it does not delete server-side data.

Key Takeaways

Delete cookies by setting their expiration time to a past value using setcookie().
Ensure path and domain parameters match those used when setting the cookie.
Call setcookie() before sending any output to the browser.
Deleting a cookie instructs the browser to remove it; it does not delete server data.
Use an empty string as the cookie value when deleting.