Paddy Hallihan
Paddy Hallihan

Reputation: 1686

Unset or delete a cookie in php

I am trying to remove some cookies that I set at a specific point in my code but they are not being fully unset or deleted.

I had just been unsetting them and then after a bit of research into this issue I seen a lot of people were setting the cookie to blank with a negative time expiry like so:

unset($_COOKIE["lifting365_last_name"]);
setcookie("lifting365_customer_id", "", time()-3600);

When I do this and then var_dump($_COOKIE); the cookies I set are not being dumped on screen. They seem to not exist any more.

However, if I navigate to another page, the cookies are back to what I had set them previously.

Is there a way to fully delete my cookies?

Upvotes: 0

Views: 912

Answers (1)

Rob Wmaster
Rob Wmaster

Reputation: 36

Using the Unset command just removes the data from the super global $_COOKIES at runtime, the actual cookie is stored on the users computer and is passed in the request which PHP then populates into the COOKIES global.

In order to remove a cookie the PATH part of the cookie needs to be the same as the current path you are in or set to '/' to be available across the entire domain.

setcookie("TestCookie", "Some Data", 0, '/');

This makes it available across the domain and will expire at the end of the session or closing of the browser.

Then to delete:

setcookie("TestCookie", "", time()-3600, '/');

I would also check the time on both the server and client are correct for testing.

Upvotes: 1

Related Questions