Reputation: 39
I am setting a cookie at first, when I close the browser the cookie is supposed to be destroyed so I am not setting any expiry time. But somehow the cookie is not getting destroyed even after closing the browser.
<?php
session_start();
if(isset($_COOKIE['favcolor']))
{
echo $_COOKIE['favcolor'];
}
else
{
$_SESSION["favcolor"] = "green";
setcookie('favcolor', 'green',0);
echo 'new cookie and session are set';
}
?>
Upvotes: 2
Views: 896
Reputation: 14126
Firstly, your code appears to be correct as presented. As stated in the PHP docs for setcookie()
:
If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).
This is known as a "session cookie" and should be deleted by the browser when it closes.
Looking into this a little, it appears that Chrome and Firefox behave a little differently depending if they are configured to remember open tabs and windows at startup, and this is by design.
You mentioned you are using Chrome - if Chrome is configured to "Continue where you left off" at startup, session cookies might not be deleted when the tab closed and browser is restarted.
I can verify that the cookie is deleted when the browser is closed when I choose "Open the New Tab page".
This is the same with Firefox - there is some additional information with some details about how you can configure this on the Mozilla support forum.
In short, it appears that you might not be able to rely on the Chrome or Firefox to guarantee deleting a session cookie.
Upvotes: 3