我正在学习PHP,我目前正在练习专业编程,我遇到了一个问题。我正在基于哈希cookie值为我的网站构建“记住我”功能,它包含两个值,标识符+哈希标识符,我将其存储在cookie中,我将标识符和哈希标识符分成用户表中的两个不同数据库行。在检查pase时我将数据库中的cookie分开,这样我就可以将标识符和散列标识符分开并与DB进行比较,首先检查是否可以,但我的问题是在第二次刷新页面后我的查询输出空字符串,因此hash_equals
函数失败。
这是我的代码:
记住用户:
/*
* if user checked "remember me" checkbox create cookie and update info in table
*/
if ($userRemember === "on") {
$rememberID = bin2hex(openssl_random_pseudo_bytes(64));
$rememberToken = hash('sha512', $rememberID);
updateRememberInfo($rememberID, $rememberToken, $userName);
setcookie("verificationToken", "{$rememberID}___{$rememberToken}", time() + 60 * 60, '/', 'localhost', false, true);
}
检查来自cookie和DB的用户信息
function checkRememberInfo() {
/*
* include DB connection
*/
global $connection;
/*
* checking if cookie exists
*/
if (isset($_COOKIE["verificationToken"])) {
/*
* geting data from cookie
* spliting data in two strings, i used triple underscore to split values in cookie
*/
$data = $_COOKIE["verificationToken"];
$credentials = explode("___", $data);
/*
* if cookie is empty or data from cookie isn't split in two array items redirect to index page
*/
if (empty(trim($data)) || count($credentials) !== 2) {
header("Location: index.php");
/*
* else perform query and check values from DB and cookie
*/
} else {
$identifier = $credentials[0];
$hashedToken = hash('sha512', $credentials[1]);
$query = mysqli_prepare($connection, "SELECT `ID`, `username`, `rememberID`, `rememberToken` FROM `users` WHERE `rememberID` = ?");
mysqli_stmt_bind_param($query, "s", $identifier);
mysqli_stmt_execute($query);
mysqli_stmt_bind_result($query, $userID, $userName, $rememberID, $rememberToken);
mysqli_stmt_fetch($query);
mysqli_stmt_close($query);
if (hash_equals($hashedToken, $rememberToken)) {
// log user in
} else {
updateRememberInfo(null, null, $userName);
}
}
}
}
我希望你能理解我和我的问题,英语不是我的母语。
修改
我已经解决了这个问题,在checkRememberInfo()函数中我哈希已经散列了部分cookie,这是错误的。