注销 PHP 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21320524/
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
Logout PHP Script
提问by user2544765
This is my script:
这是我的脚本:
<?php
// If the user is logged in, delete the session vars to log them out
session_start();
if (isset($_SESSION['user_id'])) {
// Delete the session vars by clearing the $_SESSION array
$_SESSION = array();
// Delete the session cookie by setting its expiration to an hour ago (3600)
if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time() - 3600); }
// Destroy the session
session_destroy();
}
// Delete the user ID and username cookies by setting their expirations to an hour ago (3600)
setcookie('user_id', '', time() - 3600);
setcookie('username', '', time() - 3600);
// Redirect to the home page
$home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/index.php';
header('Location: ' . $home_url);
?>
I cannot log out once logged in on the site. Do I really need cookie'd logins or can I take that out?
登录网站后,我无法注销。我真的需要用 cookie 登录吗?我可以把它去掉吗?
回答by Adam Brown
Try a simpler approach, destroy all session cookies
尝试更简单的方法,销毁所有会话 cookie
session_start();
session_destroy();
$home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/index.php';
header('Location: ' . $home_url);
回答by Abdul Aziz Al Basyir
I recommend to using this method,
我建议使用这种方法,
<?php
//User session in ['user']
if($_SESSION['user_id']){
session_start();
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
session_regenerate_id(true);
}
?>
i recommend you using that method
, why? because that method using true destroy,delete cookie in browserand new set ID of sessionof session in PHP
我建议你使用这种方法,为什么?因为该方法在 PHP 中使用true destroy,delete cookie in browser和new set ID of sessionof session
回答by steve
"In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that." see: http://us1.php.net/session_destroyand: http://us1.php.net/manual/en/function.session-id.php"Caution Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal." see: http://us2.php.net/manual/en/function.session-unset.php
“为了完全终止会话,比如注销用户,会话 id 也必须取消设置。如果使用 cookie 来传播会话 id(默认行为),则必须删除会话 cookie。setcookie()可以用来做那个。” 请参阅:http: //us1.php.net/session_destroy和:http: //us1.php.net/manual/en/function.session-id.php“注意不要用 unset($_SESSION ) 因为这将禁止通过 $_SESSION 超全局变量注册会话变量。” 见:http: //us2.php.net/manual/en/function.session-unset.php

