【发布时间】:2019-05-04 03:35:46
【问题描述】:
当用户登录或注册时,我会存储一个会话和 cookie,并在数据库中插入一些详细信息。
登录/注册.php
$_SESSION['userid'] = $userid;
$selector = base64_encode(random_bytes(9));
$authenticator = random_bytes(33);
$token = hash('sha256', $authenticator);
$expires = date('Y-m-d\TH:i:s', time() + 864000);
$stmt2 = $pdo->prepare("INSERT INTO auth_tokens
(selector,token,userid,expires) VALUES (:selector, :token, :userid,
:expires)");
$stmt2->bindParam(':selector', $selector);
$stmt2->bindParam(':token', $token);
$stmt2->bindParam(':userid', $userid);
$stmt2->bindParam(':expires', $expires);
$stmt2->execute();
setcookie(
'remember',
$selector.':'.base64_encode($authenticator),
time()+(86400 * 90),
'/',
false
);
现在,当用户单击注销时,我会销毁会话和 cookie
logout.php
session_start();
$_SESSION = array();
unset($_SESSION);
if (isset($_COOKIE['remember'])) {
unset($_COOKIE['remember']);
setcookie('remember', '', time() - 3600, '/'); // empty value and old
timestamp
}
session_destroy();
作为管理员,我想在从自己的 End 删除用户时删除用户会话和 cookie。
现在当我使用这个删除数据库中的用户时
deleteuser.php
$stmt = $pdo->prepare("DELETE FROM users WHERE id=:uid");
$stmt->bindValue(':uid', $uid);
$stmt->execute();
if($stmt){
$stmt2 = $pdo->prepare("DELETE FROM auth_tokens WHERE userid=:uid");
$stmt2->bindValue(':uid', $uid);
$stmt2->execute();
}
当同一用户重新访问一个页面(index.php)时,我在页面顶部收到此错误
警告:hash_equals():预期 known_string 是一个字符串,在第 17 行的 C:\xampp\htdocs\book\php\function.php 中给出了 null
index.php
include('php/function.php');
getcookie();
function.php
if (!empty($_COOKIE['remember'])) {
list($selector, $authenticator) = explode(':', $_COOKIE['remember']);
$stmt = $pdo->prepare("SELECT * FROM auth_tokens WHERE selector=:selector");
$stmt->bindValue(':selector', $selector);
$stmt->execute();
$row = $stmt->fetch();
if (hash_equals($row['token'], hash('sha256',
base64_decode($authenticator)))) {
.....
}
}
function getcookie (){
if (!empty($_COOKIE['remember'])) {
list($selector, $authenticator) = explode(':', $_COOKIE['remember']);
$stmt = $pdo->prepare("SELECT * FROM auth_tokens WHERE
selector=:selector");
$stmt->bindValue(':selector', $selector);
$stmt->execute();
$row = $stmt->fetch();
$toke = $row['token'];
$auth = hash('sha256', base64_decode($authenticator));
if (hash_equals($row['token'], hash('sha256',
base64_decode($authenticator)))) {
$userid = $row['userid'];
// Then regenerate login token as above
}
}
}
如何调整这些代码,以便我可以通过结束用户会话和 cookie 来有效地从我的网站中删除用户。?
【问题讨论】:
标签: php html session-cookies