Current Location: Home> Latest Articles> How to Use PHP's crypt() Function to Create a Secure User Registration and Login System?

How to Use PHP's crypt() Function to Create a Secure User Registration and Login System?

M66 2025-06-23

When building websites or applications, the security of user authentication systems is an important consideration. PHP offers various methods to encrypt and validate passwords, and the crypt() function is a classic and powerful encryption tool. This article will explain how to use the crypt() function to build a secure user registration and login system, including password encryption, validation, and handling user data.

1. Introduction to the crypt() Function

crypt() is an encryption function provided by PHP that encrypts a string using a one-way hash algorithm. It supports various encryption algorithms (such as MD5, SHA-256, SHA-512, and Blowfish), depending on the format of the provided salt.

string crypt ( string $str , string $salt )  

The value of the salt determines the type and behavior of the encryption algorithm. For security, it is recommended to use salts that support SHA-512 or Blowfish.

2. User Registration Process

During user registration, we need to encrypt the password before storing it in the database, ensuring that even if the database is compromised, attackers cannot easily reverse the password.

Example Code: User Registration

<?php  
if ($_SERVER['REQUEST_METHOD'] === 'POST') {  
    $username = $_POST['username'];  
    $password = $_POST['password'];  
$salt = '$6$' . bin2hex(random_bytes(16)) . '$';  // SHA-512  
$hashed_password = crypt($password, $salt);  

// Save the username and encrypted password to the database (using SQLite as an example)  
$db = new PDO('sqlite:users.db');  
$stmt = $db->prepare("INSERT INTO users (username, password) VALUES (?, ?)");  
$stmt->execute([$username, $hashed_password]);  

echo "Registration successful, please <a href='https://m66.net/login.php'>login</a>.";  

}
?>

HTML Registration Form:

<form method="POST" action="">  
    Username: <input type="text" name="username" required><br>  
    Password: <input type="password" name="password" required><br>  
    <input type="submit" value="Register">  
</form>  

3. User Login Process

For login, we don't need to know the original password. We simply encrypt the password entered by the user using the same salt stored in the database with crypt(), and then compare it with the stored hash.

Example Code: User Login

<?php  
if ($_SERVER['REQUEST_METHOD'] === 'POST') {  
    $username = $_POST['username'];  
    $password_input = $_POST['password'];  
$stmt = $db->prepare("SELECT password FROM users WHERE username = ?");  
$stmt->execute([$username]);  
$row = $stmt->fetch(PDO::FETCH_ASSOC);  

if ($row) {  
    $hashed_password = $row['password'];  
    if (crypt($password_input, $hashed_password) === $hashed_password) {  
        echo "Login successful! Welcome back, {$username}.";  
    } else {  
        echo "Incorrect password.";  
    }  
} else {  
    echo "User does not exist.";  
}  

}
?>

HTML Login Form:

<form method="POST" action="">  
    Username: <input type="text" name="username" required><br>  
    Password: <input type="password" name="password" required><br>  
    <input type="submit" value="Login">  
</form>  

4. Example Database Structure (SQLite)

CREATE TABLE users (  
    id INTEGER PRIMARY KEY AUTOINCREMENT,  
    username TEXT UNIQUE NOT NULL,  
    password TEXT NOT NULL  
);  

5. Security Recommendations

  • Use HTTPS: Ensure all form submissions are done over an encrypted connection.

  • Add CSRF Protection: Prevent cross-site request forgery attacks.

  • Limit Login Attempts: Prevent brute force attacks.

  • Update PHP Version Regularly: Keep encryption algorithms and functions secure.

  • Consider Using Modern Functions (e.g., password_hash): While crypt() is effective, modern PHP recommends using password_hash() and password_verify().

Conclusion

By appropriately using the crypt() function and its corresponding password validation logic, we can create a relatively secure user authentication system. Although modern PHP provides more advanced interfaces, such as password_hash(), understanding how crypt() works still helps to deepen the understanding of password encryption principles. In certain low PHP versions or specific compatibility requirements, crypt() remains a practical choice.