首页
学习
活动
专区
工具
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

回答 1

Stack Overflow用户

发布于 2018-08-08 22:47:41

Sakezz的评论非常混乱。

是的,使用加盐哈希比使用无盐哈希要好得多,但SHA是一个比MD5更安全的哈希。但是php附带了一个password_hash()函数(和a whole chapter in the manual),它为你做了所有聪明的事情,允许使用更好的散列,并简化了向新散列机制的迁移。

您正在使用一个身份验证令牌,该令牌可以被撤销,并且实际上是随机的。这很好--尽管一个用户不能同时登录到多个设备。您是否提供了用户注销的机制?(这一点很重要)。

您正在为查询使用参数绑定,这也很好,但更好的安全性方法是使用特权绝望的存储过程-并且您连接的帐户不应该具有对表的读/写访问权限。

编码风格还可以,但除非您有坚持使用它的理由,否则我建议使用psr-1 &2

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

https://stackoverflow.com/questions/51745811

复制
相关文章

相似问题

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