我想让我的网站密码保护。用户登录后,在关闭窗口或浏览器时不应注销。为此,我将身份验证令牌存储为cookie。
这是我的代码:
<?php
// take $_COOKIE['user'] if it exist, else take $_POST['user']
if(isset($_COOKIE['user'])) {
$user = $_COOKIE['user'];
} else {
$user = $_POST['user'];
}
// get login data from database
if(isset($user)) {
$stmt = $pdo->prepare('SELECT user, password, authentication_token FROM users WHERE user = :user LIMIT 1;');
$stmt->execute(array(':user' => $user));
$results = $stmt->fetchAll();
foreach($results as $row) {
$password = $row['password'];
$authentication_token = $row['authentication_token'];
}
}
// set passwort and authentication token at first visit and login
if($password == "" && isset($_POST['user'], $_POST['password'])) {
$unique_authentication_token = hash('sha256', uniqid(rand().time(), true));
$statement = $pdo->prepare("UPDATE users SET password = :password, authentication_token = :authentication_token WHERE user = :user");
$statement->execute(array(':user' => $_POST['user'], ':password' => hash('sha256', $_POST['password']), ':authentication_token' => $unique_authentication_token));
setcookie("user", $_POST['user'], time()+(10*365*24*60*60));
setcookie("authentication_token", $unique_authentication_token, time()+(10*365*24*60*60));
unset($_POST);
header('location: https://www.example.com');
exit;
}
// show login form if no data or wrong data
if(!isset($_COOKIE['user']) || !isset($_COOKIE['authentication_token']) || $_COOKIE['authentication_token'] != $authentication_token) {
$showLogin = 1;
}
// login
if(isset($_POST['user'], $_POST['password']) && hash('sha256', $_POST['password']) == $password) {
setcookie("user", $_POST['user'], time()+(10*365*24*60*60));
setcookie("authentication_token", $authentication_token, time()+(10*365*24*60*60));
unset($_POST);
header('location: https://www.example.com');
exit;
}
// login form
if($showLogin == 1) {
echo "
<form action=\"\" method=\"post\">
<select name=\"user\">
<option>George</option>
<option>Harald</option>
<option>Peter</option>
</select>
<input type=\"password\" name=\"password\" placeholder=\"Password\">
</form>
";
exit;
}
?>
这是我做的正确方式吗?你能看到任何易受攻击的地方吗?我可以做得更好吗?
https://stackoverflow.com/questions/51745811
复制相似问题