"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Verify User Passwords Securely with PHP\'s password_verify Function?

How to Verify User Passwords Securely with PHP\'s password_verify Function?

Published on 2024-11-05
Browse:670

How to Verify User Passwords Securely with PHP\'s password_verify Function?

Decrypting Encrypted Passwords with PHP

Many applications store user passwords securely using encryption algorithms like password_hash. However, when validating login attempts, it's important to compare the input password against the encrypted, stored version.

The Problem of Encryption

password_hash employs Bcrypt, a one-way hashing algorithm, meaning the encrypted password cannot be reversed or decrypted. This is a security feature that ensures that even if the database is compromised, attackers cannot access plain-text passwords.

The Solution: Password Verification

To validate user passwords, use the password_verify function:

if (password_verify('input_password', $encrypted_password)) {
    // Password matches!
} else {
    // Invalid password.
}

This function compares the input password to the encrypted version and returns true if they match.

Modifying Your SQL Query

Instead of including the input password in the SQL query, use parameterization:

$sql_script = 'SELECT * FROM USERS WHERE username=?';

This protects against SQL injection attacks by preventing malicious users from manipulating your query.

Example

Here's an example of using password_verify:

$username = $_POST['username'];
$input_password = $_POST['password'];

$sql_script = 'SELECT * FROM USERS WHERE username=?';

if ($result = $conn->query($sql_script, $username)) {
    if ($user = $result->fetch_assoc()) {
        if (password_verify($input_password, $user['password'])) {
            // Login successful!
        } else {
            // Invalid password.
        }
    } else {
        // User not found.
    }
}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3