How do you delete cookies in PHP? Also, provide an example showing how it’s done.

The interesting thing about deleting a cookie in PHP is the fact that you must use the same PHP function that you would use to create the cookie – and that is the setcookie function.

Deleting cookies using the setcookie function in PHP

The setcookie() function can actually accept up to six arguments, but only one argument is actually required — and that is the cookie name. If you use the setcookie function, and just pass a cookie name without a value, then it will have the same effect as deleting the existing cookie with the same exact name. For example, to create a cookie called first_name, you use this line:

   setcookie('first_name', 'Robert');   

And to delete the first_name cookie, you would do this:

Example of deleting a cookie in PHP:

setcookie('first_name');   

But, as an extra safety measure, you should also set the expiration time to a time in the past – as you can see below where we pass in “time() – 300” for the expiration date. This is the way we recommend that you delete the cookie in PHP:

Recommended way to delete a cookie in PHP:

setcookie('first_name', '', time()-300);   

Parameters that must be set when deleting a cookie

When you delete a cookie, you should always use the same exact parameters that were used to create the cookie in the first place. For example, If you set the domain and path when you created the cookie, then you should use those parameters again when deleting the cookie.

Other interesting facts about deleting cookies in PHP

When deleting a cookie, that deletion does not actually take effect until the page has been reloaded or another page has been accessed. This means that a cookie will still be available to a given page even after that page has deleted that cookie – but once the page is reloaded or another page is accessed in that browser window the cookie will be deleted.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.