在用户注销时删除 PHP cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13862854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deleting a PHP cookie upon user logout
提问by zealisreal
I started creating a login system which utilised cookies for a "remember me" feature. All is working fine however I am having trouble deleting the cookie upon user logout.
我开始创建一个登录系统,它利用 cookie 来实现“记住我”的功能。一切正常,但是我在用户注销时无法删除 cookie。
If a user does not check the "remember me" box and logs in successfully I.e. does not create the cookie, the logout function works as expected and loads the login box.
如果用户没有选中“记住我”框并成功登录,即没有创建 cookie,注销功能会按预期工作并加载登录框。
If they don't do the latter and the user clicks the logout button the cookie remains and it shows they are still logged in.
如果他们不执行后者并且用户单击注销按钮,则 cookie 会保留并显示他们仍处于登录状态。
If someone could shine some light as to why the cookie wont delete I would be very grateful.
如果有人能解释为什么 cookie 不会删除,我将不胜感激。
Below is the code I am using:
下面是我正在使用的代码:
PHP code that runs after a user tries to log in:
在用户尝试登录后运行的 PHP 代码:
// If the form has been submitted
if(isset($_POST['login'])):
// Protect from unwanted code/string context
$username = strip_tags(addslashes(trim($_POST['username'])));
$string = strip_tags(addslashes(trim($_POST['password'])));
$remember = strip_tags(addslashes(trim($_POST['remember'])));
// Pass the returned variables from functions to a local versions
$password = salting($string); // Salt Password Preperation
$link = db_connect(); // DB connection
// Connect to the database and try to find a login match
$result = mysqli_query($link,"SELECT * FROM web_users WHERE username='".$username."' AND password='".$password."'");
$row = mysqli_fetch_object($result);
// Create erronous results if submitted data is invalid
if (mysqli_num_rows($result) !== 1):
$errmsg[0] = "Invalid Username or Password, please re-try";
endif;
$e_login = serialize($errmsg);
// If validation passes then continue
if (!$errmsg):
// Increment the login_count field by 1
$row->login_count++;
$count = $row->login_count;
// Retrieve the date for admin purposes
$date = date('Y-m-d-h:i:s'); // Y=year (4 digits) m=month (leading zero) h=hour i=minutes s=seconds
// Salt Password Preperation
$string = session_id();
$login_id = salting($string);
// Connect to the database and update the related row
$update = mysqli_query($link,"UPDATE web_users
SET login_count='".$count."',
login_last='".$date."',
login_id='".$login_id."',
logged='1'
WHERE id='".$row->id."'")
or die(mysqli_error($link));
// Create a multi-dimensional session array
$_SESSION['login'] = array('user' => $row->display_name,
'id' => $row->id,
'user_level' => $row->user_level);
if($remember == 1):
setcookie("login_user",session_id(),time() + (86400*7)); // 604800 = 1 week
endif;
// Free the memory and close the connection
mysqli_free_result($result);
mysqli_close($link);
// Take the user to the successive page if no errors
header("location: /");
endif;
endif;
HTML code to create the logout element:
用于创建注销元素的 HTML 代码:
<a href="/logout" title="Logout">
<img src="<? echo ASSETS . IMAGES . ICONS . GENERAL; ?>logout.png" alt="User Logout">
</a>
PHP code that runs when a user logs out:
用户注销时运行的 PHP 代码:
function logout() {
// Load the db connect function to pass the link var
$link = db_connect();
if(is_array($_SESSION['login'])):
// Update the logged field to show user as logged out
$update = mysqli_query($link,"UPDATE web_users SET logged='0' WHERE id='".$_SESSION['login']['id']."'") or die(mysqli_error($link));
// Free the memory and close the connection
mysqli_free_result($update);
mysqli_close($link);
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if(isset($_COOKIE[session_name()])):
setcookie(session_name(), '', time()-7000000, '/');
endif;
// Finally, destroy the session.
session_destroy();
// Take the user to the successive page if no errors
header("location: /");
endif;
}
回答by Lumbendil
The user, when logged in with the remember me checkbox to your site, will have twocookies. The session cookie, by default PHPSESSID, and the remember me cookie, login_user. In order to remove the session, you just remove the sesion cookie with this code:
用户在使用“记住我”复选框登录您的网站时,将拥有两个cookie。默认情况下会话 cookiePHPSESSID和记住我 cookie login_user。为了删除会话,您只需使用以下代码删除会话 cookie:
if(isset($_COOKIE[session_name()])):
setcookie(session_name(), '', time()-7000000, '/');
endif;
The issue is that, aside from that, you need to unset the remember me cookie, with the following code.
问题是,除此之外,您需要使用以下代码取消设置记住我的 cookie。
if(isset($_COOKIE['login_user'])):
setcookie('login_user', '', time()-7000000, '/');
endif;
回答by giorgio
To delete a cookie, you should set the expiration date in the past:
要删除 cookie,您应该将过期日期设置为过去:
setcookie('login_user', '',time() - 3600);
You have this rule, but explicitly add the path parameter, although you have NOT used the path when setting the cookie, this might be the problem.
你有这个规则,但明确添加了路径参数,虽然你在设置cookie时没有使用路径,但这可能是问题所在。
回答by JRSofty
I would hazard a guess that your code
我会冒险猜测你的代码
if(isset($_COOKIE[session_name()])):
setcookie(session_name(),'',time()-7000000,'/');
endif;
is your problem. Most likely the issetis returning false. I would remove it from the ifstatement if possible.
是你的问题。最有可能的isset是返回false。if如果可能,我会将其从声明中删除。
Also in addition as mentioned below in the comments. Did you use session_start()? There is no reference to it in your code above. This would cause session_name()to return empty.
此外,正如下面在评论中提到的那样。你用了session_start()吗?上面的代码中没有提到它。这将导致session_name()返回空。

