PHP Hash Passwords


  • Security: Always avoid storing passwords as plain text within your database systems.
  • A hash function converts a password into a fixed-length string that resists reversal through conventional methods.
  • Despite database breaches, reversing hashes remains an extremely challenging task.

password_hash() – To Hash a Password

<?php
$password = "mysecret123";
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
echo $hashedPassword;
?> 

 

  • PASSWORD_DEFAULT: Uses the strongest available algorithm (currently BCRYPT)
  • Output is a 60-character string

password_verify() – To Verify a Password

<?php
$password = "mysecret123"; // user input
$hashFromDB = '$2y$10$L85s0nkbz6VdZjFfNOtk0utW9iR08mNCPAF6DwlKFHht3cvB.e5N2'; // from DB

if (password_verify($password, $hashFromDB)) {
    echo "Password is correct!";
} else {
    echo "Invalid password.";
}
?>  

Storing Hashed Password in a Database

<?php $conn = new mysqli("localhost", "root", "", "testdb");

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $username = $_POST["username"];
    $password = password_hash($_POST["password"], PASSWORD_DEFAULT);

    $stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();
    echo "User registered securely!";
} ?> 

Checking Password on Login

<?php $username = $_POST['username'];
$enteredPassword = $_POST['password'];

$stmt = $conn->prepare("SELECT password FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

if ($row && password_verify($enteredPassword, $row['password'])) {
    echo "Login successful!";
} else {
    echo "Invalid username or password.";
} ?> 

Task Function
Hash a password password_hash()
Verify a password password_verify()
Rehash password password_needs_rehash()
Algorithm used PASSWORD_DEFAULT



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.