K. Weber
K. Weber

Reputation: 2773

Cookie doesn't expire when closing browser

I'm trying to set a cookie with:

setcookie($cookie_name, $val, 0);

Or

setcookie($cookie_name, $val);

But when I close and re-open the browser (firefox, chrome) the cookie is still alive with the same value. How can I force it to delete when visit is over?

Thank you

Upvotes: 2

Views: 8323

Answers (6)

MoHo
MoHo

Reputation: 2583

You may need to unset the cookie and then set it null like this:

unset($_COOKIE['cookie_name']);
setcookie ( 'cookie_name', null,-1 );

in the first line, you unset it and then set it to null in case any further problem.

Upvotes: 0

Gurmukh Panesar
Gurmukh Panesar

Reputation: 132

I have experienced this similar problem with Chrome. Opening up the cookies panel in Web Developer Tools sometimes shows the cookie with Expires set to "Session". Upon closing the browser (not just the tab) and re-opening the browser this cookie still persists. A sure fire way to resolve this is to clear the cache. That seems to do the trick. Bottom line is that if the cookie is being shown as "session" in the browser tools, then you've set it correctly.

Upvotes: 0

Ben Carey
Ben Carey

Reputation: 16948

To delete a cookie just set the expiry date to the past like so:

// Set the cookie in the past to ensure it is removed
setcookie($cookie_name, $val, time()-3600);

However, I do not think this is the issue in your case, as your code seems to be correct.

How are you testing for the cookie? You are probably setting it again before testing for it!

You will also want to make sure you are closing the browser not the tab. Closing a tab, does not end a session!

Upvotes: 2

Valeriy Gorbatikov
Valeriy Gorbatikov

Reputation: 3519

Try to use this code:

setcookie ("TestCookie", "", time() - 3600);// set the time to minus to remove the cookie.

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76870

You should try

setcookie($cookie_name, $val, time()-3600);

Upvotes: 1

Mircea Soaica
Mircea Soaica

Reputation: 2817

Try setting the value as null

setcookie($cookie_name, null);

Upvotes: 1

Related Questions