简体   繁体   English

PHP - 销毁会话并删除 cookie

[英]PHP - destroy session and remove cookies

I have a problem clear cookie when session is destroyed or expired.当会话被破坏或过期时,我在清除 cookie 时遇到问题。 I create application with session (logged user) and cookies (cart) and I must clear cart when session is destroyed or expired.我使用会话(登录用户)和 cookie(购物车)创建应用程序,当会话被破坏或过期时,我必须清除购物车。 I'm tring use $_SESSION[SESSION_NAME], but not always $_SESSION[SESSION_NAME] has been removed after destroy or expire.我正在尝试使用 $_SESSION[SESSION_NAME],但并非总是在销毁或过期后删除 $_SESSION[SESSION_NAME]。

if(!isset($_COOKIE[SESSION_NAME])) {
   clearCookie();
}

When I remove cookie with session ID then cookies has been cleared, but when session expire then cookie (and cookie with session ID) have been existed.当我删除带有会话 ID 的 cookie 时,cookie 已被清除,但是当会话过期时,cookie(和带有会话 ID 的 cookie)已经存在。

I'm tried all session functions ( https://www.php.net/manual/en/ref.session.php ), but I'm not found good solution.我尝试了所有会话功能( https://www.php.net/manual/en/ref.session.php ),但没有找到好的解决方案。 How to clear cookie when session has been removed or expired?如何在会话被删除或过期时清除 cookie?

As your cookie is identified by data from your session , it would be logical to delete/clear the cookie before destroying the session.由于您的cookie是由会话中的数据标识的,因此在销毁会话之前删除/清除 cookie 是合乎逻辑的。

So, whenever you need to destroy the session, first clear the cookie, then destroy your session.因此,每当您需要销毁会话时,请先清除 cookie,然后再销毁您的会话。

Something like this:像这样的东西:

clearCookie();
unset($_SESSION);
session_destroy();

set cookie value to the past date将 cookie 值设置为过去的日期

setcookie($cookie_name, '', time() - (86400 * 30), "/","");  // 86400 = 1 day
session_destroy();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM