Skip to content
Advertisement

Destroy cookie when browser window closes PHP

I have created a popup in WordPress that will open when visitor IP is from Australia. The popup will show up on page load. I want to make it not show until the browser screen is closed.

For this, I used the cookie. I set the cookie when the close button is clicked and creating the cookie in PHP using ajax.

Here is the code I am using to create cookie:

 setcookie("stay_here", "yes", 0, "/");

I set the cookie time to 0 so that it will destroy when the browser closed. The issue is that the site has user account area and when the user is logged in the session of the user is created. This session is not destroying after closing the browser. And when the above cookie created it automatically set expiration time as “Session”.

I checked this on firefox and the data variable “Expires” of the cookie is set as “Session”. As the session is not destroying when I close the browser and the cookie Expires value which is set as Session is also not destroying.

But I want the only cookie to be destroyed when the browser is closed not the Session.

I hope you understand my issue.

Can you guys look at the issue and provide me a solution to achieve this situation.

Thanks in Advance.

Advertisement

Answer

Ideally cookie created through SETCOOKIE function in PHP with its expire time 0, it will be deleted from browser when you will close the tab and time can’t be overwrite with session’s cookie time.

Try to create 1 test.php page and write setcookie(“stay_here”, “yes”, 0, “/”); code and check from browser’s cookie information.

You can also, set session cookie’s time to 0 so session cookie will also deleted when browser will be closed.

ini_set(‘session.cookie_lifetime’, 0);

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement