How To Hash Password In Php

In this blog post, we will learn how to securely hash passwords in PHP. Hashing passwords is an essential step in storing user credentials, as it makes it nearly impossible for attackers to retrieve the original password if the hash is obtained. PHP provides built-in functionality for password hashing and verification using the password_hash() and password_verify() functions.

Hashing Passwords with PHP

To hash a password in PHP, we can use the password_hash() function. This function accepts a plain-text password and a hashing algorithm as its arguments and returns the hashed password. The most recommended algorithm to use is PASSWORD_DEFAULT, which will always use the latest and most secure algorithm available.

Let’s see an example:

This code will output a hashed password similar to the following:


Verifying a Password Against a Hash

To verify a password against a stored hash, we can use the password_verify() function. This function takes two arguments: the plain-text password and the stored hashed password. If the password matches the hash, the function returns true; otherwise, it returns false.

Here’s an example:

Rehashing Passwords

It’s essential to keep the hashing algorithm up to date to maximize security. When a newer, more secure algorithm becomes available, you can rehash the stored passwords using the new algorithm. To check if a password needs to be rehashed, use the password_needs_rehash() function:

Now you know how to securely hash and verify passwords in PHP using the built-in functions password_hash(), password_verify(), and password_needs_rehash(). Remember always to keep your hashing algorithms up to date and never store plain-text passwords in your database.