使用MySQL数据和哈希密码登录PHP [英] PHP login using MySQL data and hashed password

查看:106
本文介绍了使用MySQL数据和哈希密码登录PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用MySQL数据库中的用户名和密码通过PHP登录,该用户名和密码保存了userID,用户名和hashed_pa​​sswords(我之前使用注册表格创建的,而md5哈希的盐是:2155).

I'm trying to login through PHP using a usernames and passwords from a MySQL database that saves userID, usernames, and hashed_passwords (that I created earlier using a registration form, and the salt for the md5 hash is: 2155).

问题是我无法获得未加密的密码才能用于登录.

The problem is I'm not able to get the password to be unencrypted to use it for the login.

而且我不确定这是否是如何对查询进行编码以根据用户输入从数据库中查找用户名和密码.

And I'm not sure if this is how to code the query to look for username and password from the database based on the user input.

$sql = "SELECT * FROM user where username = '$_POST["username"]' AND password = '$_POST["password"]";
$rows = $conn->query($sql);

        if ($userID > 0){
                    echo "Hello World";
            header("Location: login_success.php");
        }

        else{
                        echo "Unsuccessful";
            header("Location: index.php");
        }

推荐答案

而不是使用MD5或尝试解密密码(如此处其他建议一样),只需使用PHP的本机

Rather than using MD5 or trying to decrypt the password - as others here have suggested - simply use PHP's native password_hash() function which automatically checks if the password is correct for you.

像这样加密密码:

$unencrypted_password = 'secret!'; 
$encrypted_password = password_hash($unencrypted_password,  PASSWORD_DEFAULT);

然后像这样插入数据库:

Then insert into your DB like so:

INSERT INTO users (encrypted_password, username) VALUES ($encrypted_password, $username);

要检查密码是否正确时,请使用以下命令从数据库中选择密码:

When you want to check if the password is correct, select the password from the database with:

SELECT encrypted_password FROM users WHERE username = $username;

最后,通过使用 passoword_verify():

$correct = password_verify($unecnrypted_password, $encrypted_password);
if($correct == true) {
    echo 'correct password!';
} else {
    echo 'password incorrect!';
}

要小心防止SQL注入,因为上面的代码容易受到攻击.

Be careful to protect against SQL-injection, as the above code is vulnerable to it.

这篇关于使用MySQL数据和哈希密码登录PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆