HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Password Hashing

Storing user passwords in plain text is one of the biggest security risks a developer can take. If your database is ever compromised, hackers would have instant access to all user accounts. To prevent this, PHP provides a native Password Hashing API to secure credentials.


Hashing vs. Encryption

  • Encryption: A two-way process. Data can be scrambled with a key and unscrambled later.
  • Hashing: A one-way process. A password is turned into a unique "fingerprint" (hash) that cannot be reversed to reveal the original password.

1. Creating a Hash: password_hash()

When a user registers, you should hash their password before saving it to the database. The password_hash() function handles everything, including salting and choosing a strong algorithm (usually BCrypt).

<?php
    $password = "mySecretPassword123";

    // Hash the password using the default algorithm
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    echo $hashedPassword; 
    // Output: $2y$10$QjSHW965iaZp... (a long, secure string)
?>
Why PASSWORD_DEFAULT? This tells PHP to use the current strongest algorithm. As PHP evolves, this algorithm may change (e.g., from BCrypt to Argon2), keeping your hashes secure without you changing any code.

2. Verifying a Password: password_verify()

When a user tries to log in, you retrieve the hashed password from the database and compare it to what the user just typed using password_verify().

<?php
    $userTypedPassword = "mySecretPassword123";
    $hashedFromDatabase = "$2y$10$QjSHW965iaZp..."; // The hash you saved earlier

    if (password_verify($userTypedPassword, $hashedFromDatabase)) {
        echo "Password is valid! Access granted.";
    } else {
        echo "Invalid password. Access denied.";
    }
?>

Summary of the Workflow

  1. Registration: Get password -> password_hash() -> Store Hash in DB.
  2. Login: Get password -> Fetch Hash from DB -> password_verify().
Security Rule: Never use outdated hashing algorithms like md5() or sha1() for passwords. They are extremely fast, which makes them easy for hackers to crack using "Brute Force" attacks.

Why is this secure?

  • Irreversible: Even if a hacker sees the hash, they can't tell what the password is.
  • Unique Salts: Even if two users have the same password, their hashes will look completely different because PHP adds a random "salt" automatically.
  • Cost Factor: BCrypt is designed to be slow, making it much harder for hackers to try millions of combinations per second.
Tip: Ensure your database column for the password hash is at least 255 characters long to accommodate future, longer hashing algorithms.

Summary

  • Hashing is a one-way security measure for passwords.
  • password_hash() creates the secure string.
  • password_verify() checks if a password matches a hash.
  • Always use PASSWORD_DEFAULT.
  • Never store passwords in plain text.