0
0
PHPprogramming~5 mins

Password hashing with password_hash in PHP

Choose your learning style9 modes available
Introduction

We use password hashing to keep passwords safe. Instead of saving the password directly, we save a secret code that is hard to guess.

When creating a new user account and saving their password.
When checking if a user's login password is correct.
When updating a user's password securely.
When you want to protect user data from hackers.
When storing passwords in a database.
Syntax
PHP
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

password_hash creates a safe version of the password.

PASSWORD_DEFAULT chooses the best hashing method available.

Examples
This creates a hashed password from a simple password string.
PHP
$password = 'mypassword123';
$hashed = password_hash($password, PASSWORD_DEFAULT);
echo $hashed;
This uses the BCRYPT method explicitly to hash the password.
PHP
$password = 'secret!';
$hashed = password_hash($password, PASSWORD_BCRYPT);
echo $hashed;
This uses the ARGON2ID method, a newer and strong hashing algorithm.
PHP
$password = 'hello';
$hashed = password_hash($password, PASSWORD_ARGON2ID);
echo $hashed;
Sample Program

This program shows how to hash a password and print both the original and hashed versions.

PHP
<?php
$password = 'MySafePass123!';
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
echo "Original password: $password\n";
echo "Hashed password: $hashedPassword\n";
?>
OutputSuccess
Important Notes

The hashed password looks like a long random string.

Never store or show the original password after hashing.

Use password_verify to check if a password matches the hash.

Summary

Use password_hash to turn passwords into safe codes.

Always use PASSWORD_DEFAULT or a strong algorithm.

Check passwords with password_verify when users log in.