How To Encrypt and Verify Password in PHP Tutorial

Share this Article
Reading Time: 3 minutes
433 Views

Inside this article we will see the concept i.e How To Encrypt and Verify Password in PHP Example Tutorial. Article contains the classified information about password encryption and verification in PHP.

PHP provides functions to encrypt password along with the algorithm type and also the function for decryption. So, if you are looking for a solution to Create a secure password in PHP then this article will help you with this. Security related PHP functions included in PHP after version v5.5.

PHP provides functions as password_hash() to generate a hash from the string and method password_verify() to verify that the given hash matches the given password.

Having a secured and strong password is always important to web applications to avoid the chances of Brute force attack or any other security breach.

Learn More –

Let’s get started.

How To Encrypt Password in PHP

To encrypt password in PHP we use password_hash() to generate a new password hash from the string.

There are algorithms (PASSWORD_DEFAULT, PASSWORD_BCRYPT, PASSWORD_ARGON2I, PASSWORD_ARGON2ID ) supported by this function.

Let’s use PASSWORD_DEFAULT algorithm to generate password hash. Hash contains 60 characters.

<?php
  
  $userPassword = "mypassword@123";
  
  $passwordHash = password_hash($userPassword, PASSWORD_DEFAULT);
  
  echo "Generated Password: " . $passwordHash;

Output

Generated Password: $2y$10$AqtJMX9YfkLlF1ZXgsaLzu02aqY1HK5/uELya2blIZhxNr7kjDjKW

How To Verify Hashed Password in PHP

To verify a password in PHP we use password_verify() to verify that the given hash that generated by password_hash(), matches the given password. The method returns true if the password and hash match otherwise it return false.

<?php
  
  $userPassword = "mypassword@123";
  
  $hash = "$2y$10$AqtJMX9YfkLlF1ZXgsaLzu02aqY1HK5/uELya2blIZhxNr7kjDjKW";
  
  $verified = password_verify($userPassword, $hash);
  
  if ($verified) {
    
    echo 'Password is verified!';
  } else {

    echo 'Password is not correct!';
  }

Output

Password is verified!

We hope this article helped you to learn How To Encrypt and Verify Password in PHP Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Get PHP Web Development Courses on Offer in just ₹299
Get PHP Web Development Courses on Offer in just ₹299