首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何密码保护网站和保持用户登录,使用PHP?

如何密码保护网站和保持用户登录,使用PHP?
EN

Stack Overflow用户
提问于 2018-08-08 19:40:25
回答 1查看 143关注 0票数 -2

我想让我的网站密码保护。用户登录后,在关闭窗口或浏览器时不应注销。为此,我将身份验证令牌存储为cookie。

这是我的代码:

代码语言:javascript
复制
<?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;
}
?>

这是我做的正确方式吗?你能看到任何易受攻击的地方吗?我可以做得更好吗?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51745811

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档