dongyoudi1342
dongyoudi1342
2018-07-05 08:12

浏览器窗口关闭PHP时销毁cookie

已采纳

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dongmi1864 dongmi1864 3年前

    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);

    点赞 评论 复制链接分享
  • duanjiao7440 duanjiao7440 3年前

    See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

    It states under "Session cookies":

    However, web browsers may use session restoring, which makes most session cookies permanent, as if the browser was never closed.

    In short: There is no reliable way to detect if a browser was closed.

    What you can do is make a cookie that will expire in 12 hours:

    setcookie("last_page_hit",$PHP_SELF,time()+12*60*60,"/");
    

    if that cookie is absent you assume it is a new visit to the site and you show the popup again.

    点赞 评论 复制链接分享
  • dtz55359 dtz55359 3年前

    You can use sessionStorage https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage It will store on clients side until window is closed. It's relatively new feature, so you should check if it's supported by your clients browsers.

    点赞 评论 复制链接分享

相关推荐