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:
<code class="php">if (password_verify('input_password', $encrypted_password)) { // Password matches! } else { // Invalid password. }</code>
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:
<code class="php">$sql_script = 'SELECT * FROM USERS WHERE username=?';</code>
This protects against SQL injection attacks by preventing malicious users from manipulating your query.
Example
Here's an example of using password_verify:
<code class="php">$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. } }</code>
The above is the detailed content of How to Verify User Passwords Securely with PHP\'s password_verify Function?. For more information, please follow other related articles on the PHP Chinese website!