Skip to content
PHP Logo

How can PHP's crypt() function be used to encrypt passwords for comparison with .htaccess passwords?

To encrypt passwords for comparison with .htaccess passwords using PHP's crypt() function, you can generate a hashed password using crypt() and then store it in your .htpasswd file. When a user logs in, you can use crypt() to hash the entered password and compare it with the hashed password in the .htpasswd file to authenticate the user.

php
// Generate hashed password for .htpasswd file
$htpasswd_password = crypt('password');

// Store $htpasswd_password in your .htpasswd file

// User login authentication
$user_input_password = 'password'; // Password entered by user
$stored_password = 'hashed_password_from_htpasswd'; // Retrieve hashed password from .htpasswd file

if (crypt($user_input_password, $stored_password) === $stored_password) {
    // Passwords match, user authenticated
    echo 'Login successful';
} else {
    // Passwords do not match
    echo 'Login failed';
}