0
0
PHPprogramming~15 mins

Password hashing with password_hash in PHP - Deep Dive

Choose your learning style9 modes available
Overview - Password hashing with password_hash
What is it?
Password hashing with password_hash is a way to safely store passwords by turning them into a secret code that is hard to reverse. Instead of saving the actual password, the program saves this code, so even if someone steals it, they can't easily find the original password. PHP provides a built-in function called password_hash to do this securely and easily. It uses strong methods to protect passwords from hackers.
Why it matters
Without password hashing, if a hacker gets access to stored passwords, they can see everyone's real passwords and cause harm. Password hashing protects users by making stolen data useless for attackers. It helps keep online accounts safe and builds trust in websites and apps. Without it, data breaches would be much more damaging and common.
Where it fits
Before learning password_hash, you should understand basic PHP syntax and how to handle user input. After mastering password hashing, you can learn about password verification with password_verify and advanced security practices like salting and peppering passwords.
Mental Model
Core Idea
Password hashing transforms a password into a fixed secret code that cannot be turned back into the original password, protecting it from theft.
Think of it like...
It's like turning your house key into a unique, one-way mold that fits only your lock but can't be used to recreate the original key if lost.
Password Input
    ↓
┌─────────────────┐
│  password_hash  │  -- One-way function
└─────────────────┘
    ↓
Hashed Password (stored safely)

When checking:
User Input Password
    ↓
┌─────────────────┐
│ password_verify │  -- Compares input with stored hash
└─────────────────┘
    ↓
True or False (access granted or denied)
Build-Up - 7 Steps
1
FoundationWhat is password hashing
🤔
Concept: Introduce the idea of turning passwords into secret codes that protect them.
When users create passwords, storing them as plain text is risky. Password hashing changes the password into a fixed-length string that looks random. This string is called a hash. Hashes are one-way, meaning you can't get the original password back from the hash.
Result
You understand why storing plain passwords is unsafe and how hashing protects them.
Knowing that hashes are one-way explains why they keep passwords safe even if stolen.
2
FoundationUsing password_hash function
🤔
Concept: Learn how to use PHP's password_hash function to create a secure hash.
In PHP, you can create a password hash by calling password_hash with the password and a hashing algorithm. For example: $password = 'mypassword'; $hash = password_hash($password, PASSWORD_DEFAULT); the PASSWORD_DEFAULT option uses a strong algorithm automatically.
Result
You get a hashed string that looks like random characters, safe to store in a database.
Using password_hash removes the need to choose or manage complex hashing algorithms yourself.
3
IntermediateVerifying passwords with password_verify
🤔Before reading on: do you think you can compare a password directly to its hash? Commit to yes or no.
Concept: Learn how to check if a password matches a stored hash using password_verify.
You cannot compare a password directly to its hash because the hash is one-way. Instead, use password_verify: if (password_verify($inputPassword, $storedHash)) { echo 'Password is correct'; } else { echo 'Password is wrong'; } This function hashes the input and compares it safely.
Result
You can check if a user entered the right password without exposing the original password.
Understanding password_verify is key to safely authenticating users without reversing hashes.
4
IntermediateWhy use PASSWORD_DEFAULT constant
🤔Before reading on: do you think PASSWORD_DEFAULT always uses the same algorithm forever? Commit to yes or no.
Concept: PASSWORD_DEFAULT lets PHP choose the best current algorithm and can change over time.
PASSWORD_DEFAULT uses the strongest algorithm available in your PHP version. This means your code stays secure as PHP updates. For example, it might use bcrypt now and switch to argon2 later. You don't have to change your code to get better security.
Result
Your password hashing stays strong automatically as PHP improves.
Using PASSWORD_DEFAULT future-proofs your password security without extra work.
5
IntermediateUnderstanding password hashing options
🤔
Concept: Learn about optional settings like cost that control hashing strength and speed.
password_hash accepts options like 'cost' which controls how slow the hashing is. Higher cost means stronger security but slower hashing: $options = ['cost' => 12]; $hash = password_hash($password, PASSWORD_DEFAULT, $options); Default cost is usually 10. Adjusting cost balances security and performance.
Result
You can customize hashing to fit your server's speed and security needs.
Knowing how to tune cost helps protect against attacks while keeping your app responsive.
6
AdvancedHandling hash updates with password_needs_rehash
🤔Before reading on: do you think password hashes stay valid forever without changes? Commit to yes or no.
Concept: Learn how to detect when stored hashes need updating to stronger algorithms or options.
PHP provides password_needs_rehash to check if a stored hash uses old settings: if (password_needs_rehash($storedHash, PASSWORD_DEFAULT, $options)) { $newHash = password_hash($password, PASSWORD_DEFAULT, $options); // Update stored hash } This helps keep password security up to date over time.
Result
You can maintain strong password security as best practices evolve.
Understanding rehashing prevents weak legacy hashes from staying in your database unnoticed.
7
ExpertSecurity pitfalls and best practices
🤔Before reading on: do you think storing the password hash in a cookie is safe? Commit to yes or no.
Concept: Explore common mistakes and how to avoid them when using password_hash in real systems.
Never store password hashes in cookies or expose them to users. Always use HTTPS to protect data in transit. Combine password_hash with other security layers like rate limiting and multi-factor authentication. Also, never try to create your own hashing method; rely on password_hash for safety.
Result
You build robust, secure authentication systems that resist common attacks.
Knowing real-world security practices prevents vulnerabilities beyond just hashing.
Under the Hood
password_hash uses strong cryptographic algorithms like bcrypt or argon2 to transform passwords into hashes. These algorithms add a random salt automatically, which means even the same password produces different hashes each time. The hashing process is slow by design to make brute-force attacks expensive. The hash stores the salt and algorithm info inside it, so password_verify can check passwords without separate data.
Why designed this way?
This design protects passwords even if the database leaks. Automatic salting prevents attackers from using precomputed tables (rainbow tables). Slow hashing reduces the speed of guessing attacks. Embedding algorithm info in the hash allows future-proof verification and easy upgrades without breaking existing hashes.
User Password
    ↓
┌─────────────────────────────┐
│ password_hash function      │
│ - Adds random salt          │
│ - Uses slow algorithm       │
│ - Embeds salt & algo info  │
└─────────────────────────────┘
    ↓
Stored Hash (salt + hash + algo)

Verification:
Input Password + Stored Hash
    ↓
┌─────────────────────────────┐
│ password_verify function    │
│ - Extracts salt & algo info │
│ - Hashes input password     │
│ - Compares hashes           │
└─────────────────────────────┘
    ↓
True or False
Myth Busters - 4 Common Misconceptions
Quick: do you think password_hash encrypts passwords so they can be decrypted later? Commit to yes or no.
Common Belief:Password hashing encrypts passwords and can be reversed to get the original password.
Tap to reveal reality
Reality:Password hashing is one-way and cannot be reversed to reveal the original password.
Why it matters:Believing hashes can be reversed leads to insecure designs that store passwords in decryptable ways, risking user security.
Quick: do you think you should manually add a salt before using password_hash? Commit to yes or no.
Common Belief:You must add your own salt before calling password_hash for security.
Tap to reveal reality
Reality:password_hash automatically generates a secure random salt; manual salting is unnecessary and can cause errors.
Why it matters:Adding manual salts can break the function's security guarantees and cause verification failures.
Quick: do you think the same password always produces the same hash with password_hash? Commit to yes or no.
Common Belief:The same password always creates the same hash output.
Tap to reveal reality
Reality:Each call to password_hash produces a different hash due to random salt, even for the same password.
Why it matters:Expecting identical hashes can cause confusion and incorrect password checks.
Quick: do you think password_verify can tell you the hashing algorithm used? Commit to yes or no.
Common Belief:password_verify cannot detect which algorithm was used to create the hash.
Tap to reveal reality
Reality:The hash stores algorithm info, and password_verify uses it automatically to verify passwords.
Why it matters:Knowing this helps you trust password_verify to handle multiple algorithms and upgrades seamlessly.
Expert Zone
1
password_hash embeds the salt and algorithm info inside the hash string, enabling seamless verification and future upgrades without extra storage.
2
The cost parameter affects hashing time exponentially, so small changes can greatly impact performance and security balance.
3
password_needs_rehash helps maintain security over time by detecting outdated hashes, but it requires rehashing only after successful password verification.
When NOT to use
Avoid using password_hash for non-password data or where reversible encryption is needed. For data that must be decrypted later, use proper encryption methods like OpenSSL. Also, do not use legacy hashing functions like md5 or sha1 for passwords; they are insecure.
Production Patterns
In real systems, password_hash is combined with secure user input handling, HTTPS, and multi-factor authentication. Systems often implement automatic rehashing on login to upgrade hashes silently. Rate limiting and account lockouts protect against brute-force attacks. Hashes are stored in dedicated user tables with strict database access controls.
Connections
Cryptographic Hash Functions
password_hash builds on cryptographic hash functions by adding salting and slow hashing.
Understanding basic hash functions helps grasp why password_hash adds salt and slowness for security.
One-way Functions in Mathematics
Password hashing is a practical example of one-way functions used in math and computer science.
Knowing one-way functions explains why hashes can't be reversed, a key security property.
Lock and Key Security Systems
Password hashing mimics physical lock systems where keys can't be copied from the lock itself.
This cross-domain view helps appreciate the importance of one-way protection in security.
Common Pitfalls
#1Storing plain passwords in the database.
Wrong approach:$password = $_POST['password']; // Directly store user password $stored = $password; // Save $stored in database
Correct approach:$password = $_POST['password']; $stored = password_hash($password, PASSWORD_DEFAULT); // Save $stored in database
Root cause:Misunderstanding that plain passwords are unsafe and that hashing is necessary before storage.
#2Comparing password and hash directly with == operator.
Wrong approach:if ($inputPassword == $storedHash) { echo 'Access granted'; }
Correct approach:if (password_verify($inputPassword, $storedHash)) { echo 'Access granted'; }
Root cause:Not knowing that hashes are not equal to the original password string and require special verification.
#3Manually adding salt before password_hash.
Wrong approach:$salt = 'randomsalt'; $hash = password_hash($salt . $password, PASSWORD_DEFAULT);
Correct approach:$hash = password_hash($password, PASSWORD_DEFAULT);
Root cause:Believing manual salting is needed despite password_hash handling it internally.
Key Takeaways
Password hashing transforms passwords into secure, one-way codes that protect user data even if stolen.
PHP's password_hash function automatically handles salting and uses strong algorithms, making it easy and safe to use.
Always verify passwords with password_verify instead of direct comparison to hashes.
Using PASSWORD_DEFAULT future-proofs your code by automatically upgrading to stronger algorithms over time.
Understanding and applying password_needs_rehash helps keep password security strong as best practices evolve.