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.