Course Content
State Management
0/1
Regular Expressions?
0/1
About Lesson

What is Password_hash() and Password_verify()?

The password_hash() and password_verify() functions are used in PHP to securely hash and verify passwords, respectively. These functions are crucial for securely storing and managing user passwords in web applications. Here’s how they work

password_hash() Function:

The password_hash() function is used to securely hash a password using a strong hashing algorithm, such as bcrypt or Argon2.

It takes the user’s plain-text password as input and returns a hashed password string.

The hashed password includes the algorithm, cost, and salt used for hashing, so there’s no need to store the salt separately.

Syntax:

string password_hash(string $password, int $algorithm, array $options = [])

Example:

PHP
$password = 'my_secure_password';

$hashed_password = password_hash($password, PASSWORD_DEFAULT);

password_verify() Function:

The password_verify() function is used to verify whether a given plain-text password matches the hashed password stored in the database.

It takes the user’s plain-text password and the hashed password as input and returns true if the passwords match, or false otherwise.

Syntax:

bool password_verify(string $password, string $hashed_password)

Example:

PHP
<?php

$entered_password = 'my_secure_password';

$stored_hashed_password = '$2y$10$yourhashedpasswordhere';

if (password_verify($entered_password, $stored_hashed_password)) {

    echo 'Password is correct';

} else {

    echo 'Password is incorrect';

}

?>

Key Points:

  • Use password_hash() to hash user passwords during registration or password updates.
  • Store the hashed passwords in the database.
  • Use password_verify() to verify user passwords during login attempts.
  • Always use password_hash() with a strong hashing algorithm (e.g., bcrypt) and an appropriate cost factor to mitigate brute force attacks.
  • Avoid using insecure hashing algorithms like MD5 or SHA1 for password hashing.

By using password_hash() and password_verify() functions correctly, you can enhance the security of user passwords in your PHP applications and protect them against unauthorized access and password-related vulnerabilities.