如何使用 PDO 的密码散列来使我的代码更安全? [英] How do I use password hashing with PDO to make my code more secure?
本文介绍了如何使用 PDO 的密码散列来使我的代码更安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码实际上可以工作,但它根本不安全,我不想使用 MD5,因为它不是那么安全.我一直在寻找密码散列,但我不确定如何将它合并到我的代码中.
My code is actually working but it's not at all secure, I don't want to use MD5 as it's not all that secure. I've been looking up password hashing but I'm not sure how I would incorporate it into my code.
登录:
require_once __DIR__.'/config.php';
session_start();
$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_USERNAME, DB_USERNAME, DB_PASSWORD);
$sql = "SELECT * FROM users WHERE username = :u AND password = :p";
$query = $dbh->prepare($sql); // prepare
$params = array(":u" => $_POST['username'], ":p" => $_POST['password']);
$query->execute($params); // execute
$results = $query->fetchAll(); // then fetch
//hash passwords pls
if (count($results) > 0 ){
$firstrow = $results[0];
$_SESSION['username'] = $firstrow['username'];
echo "Hello $username you have successfully logged in";
//header ("location:.php");
}
else{
echo "Login Has Failed";
return;
}
注册:
$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_USERNAME, DB_USERNAME, DB_PASSWORD);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$stmt = $dbh->prepare("insert into users set username='".$username."', email='".$email."', password='".$password."' ");
$stmt->execute();
echo "<p>Thank you, you are registered</p>";
谁能告诉我如何将它合并到我拥有的代码中?
Could anyone show me how to incorporate it into the code I have?
推荐答案
只需使用一个库.严重地.它们存在是有原因的.
Just use a library. Seriously. They exist for a reason.
- PHP 5.5+:使用
password_hash()
- PHP 5.3.7+:使用
password-compat
(上述的兼容包) - 所有其他人:使用 phpass
不要自己做.如果您正在创建自己的盐,您做错了.您应该使用一个可以为您处理这些问题的库.
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
并在登录时:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
这篇关于如何使用 PDO 的密码散列来使我的代码更安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文