且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用MySQL数据和哈希密码登录PHP

更新时间:2023-12-03 20:04:58

而不是使用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.