php mysql登录密码判断,使用MySQL数据和密码哈希登录PHP

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");

}

解决方案

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.

Encrypt the password like this:

$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;

Finally, check that the password is correct by using passoword_verify():

$correct = password_verify($unecnrypted_password, $encrypted_password);

if($correct == true) {

echo 'correct password!';

} else {

echo 'password incorrect!';

}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值