Password Hashing in PHP

In this tutorial, you will how to use the Different built-in functions of PHP for encrypting or hashing passwords. The tutorial aims to provide a reference for students or self-learners that are learning and planning to develop an application using PHP Language. The tutorial can help you to secure your application's user password. Here, snippets and a sample login and registration source code that demonstrates the password hashing or encryption are provided and free to download.

What is Hashing?

Hashing is a way or process that converts or transforms any given string or key into an encrypted value. In programming, it generates a new value according to the mathematical algorithm that is available to programming languages. This process is commonly used for encrypting passwords.

What are the Different built-in functions in PHP for hashing?

PHP comes with multiple functions and some of them are used for hashing keys or values. The below functions are the most common and used for hashing a string.

  • md5() - a hashing function of PHP that calculate the md5 hash of the given string.
  • sha1() - a hashing function of PHP that calculate the sha1 hash of the given string.
  • hash() - a hashing function of PHP that generates a hash value of the given string or key. This function can generate hash values using multiple algorithms such as md5, sha256, etc.
  • password_hash() - a hashing function for generating the password hash value. This function generates a strong one-way hashing algorithm and also supports multiple other algorithms.

Sample Hash Generation

simple login and registration

What is the Best Function to Encrypt Passwords in PHP?

Encrypting the passwords of your site users is the best practice and feature that must implement for a certain site or web application. It is one of the ways for securing your site data from malicious hackers.

The best hashing function for securing your users' passwords is the password_hash(). Although MD5 and SHA1 functions can be also used for hashing passwords, these functions are too weak, simple, and not-salted hashes that are vulnerable to rainbow tables and dictionary attacks. Furthermore, requiring your users to provide a password such as a password that contains an alphanumeric with valid symbols and characters will result in a strong password and complicated for hackers to decrypt.

Example

Here are some scripts of an example web application that demonstrate the usage of the password_hash() function of PHP. The application is a simple login and registration system for a certain site.

Database Schema

Database Name: sample_login

  1. CREATE TABLE `users` (
  2. `name` text NOT NULL,
  3. `email` text NOT NULL,
  4. `password` text NOT NULL

Registration

The below script contains the HTML code for the registration form page interface and PHP codes for hashing the password and inserting the user details into the database.

register.php

  1. <?php
  2. if($_SERVER['REQUEST_METHOD'] == 'POST'){
  3. include_once("db-connect.php");
  4. extract($_POST);
  5. $password = password_hash($password, PASSWORD_DEFAULT);
  6. $check_duplicate = $conn->query("SELECT id FROM `users` where `email` = '{$email}'")->num_rows;
  7. if($check_duplicate < 1){
  8. $sql = "INSERT INTO `users` (`name`, `email`, `password`) VALUES ('{$name}', '{$email}', '{$password}')";
  9. $insert = $conn->query($sql);
  10. if($insert){
  11. echo "<script> alert('Account has been created successfully.'); location.replace('login.php');</script>";
  12. exit;
  13. }else{
  14. echo "<script> alert('Registration Failed!.');</script>";
  15. }
  16. }else{
  17. echo "<script> alert('Registration Failed! Email already exists.');</script>";
  18. }
  19. }
  20. ?>
  21. <!DOCTYPE html>
  22. <html lang="en">
  23. <meta charset="UTF-8">
  24. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  25. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  26. <title>PHP - Password Hashing</title>
  27. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  28. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  29. <link rel="stylesheet" href="assets/css/styles.css">
  30. <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script>
  31. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  32. <script src="assets/js/script.js"></script>
  33.  
  34. </head>
  35. start_loader()
  36. </script>
  37. <main>
  38. <nav class="navbar navbar-expand-lg navbar-dark bg-gradient">
  39. <div class="container">
  40. <a class="navbar-brand" href="./">PHP - Password Hashing</a>
  41. <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
  42. <span class="navbar-toggler-icon"></span>
  43. </button>
  44. <div class="collapse navbar-collapse" id="navbarNav">
  45. <ul class="navbar-nav">
  46. <li class="nav-item">
  47. <a class="nav-link" href="./">Home</a>
  48. </li>
  49. <li class="nav-item">
  50. <a class="nav-link" href="login.php">Login</a>
  51. </li>
  52. <li class="nav-item">
  53. <a class="nav-link active" aria-current="page" href="register.php">Registration</a>
  54. </li>
  55. </ul>
  56. </div>
  57. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  58. </div>
  59. </nav>
  60. <div id="main-wrapper">
  61. <div class="container-md px-5 my-3">
  62. <div class="col-lg-7 col-md-8 col-sm-10 col-xs-12 mx-auto">
  63. <div class="card rounded-0 shadow">
  64. <div class="card-header rounded-0">
  65. <div class="card-title"><b>Registration</b></div>
  66. </div>
  67. <div class="card-body rounded-0">
  68. <div class="container-fluid">
  69. <form action="" id="register" method="POST">
  70. <div class="mb-3">
  71. <label for="name" class="form-label fw-light">Name</label>
  72. <input type="text" class="form-control rounded-0" name="name" id="name" value="<?= $_POST['name'] ?? "" ?>" required>
  73. </div>
  74. <div class="mb-3">
  75. <label for="email" class="form-label fw-light">Email</label>
  76. <input type="text" class="form-control rounded-0" name="email" id="email" value="<?= $_POST['email'] ?? "" ?>" required>
  77. </div>
  78. <div class="mb-3">
  79. <label for="password" class="form-label fw-light">Password</label>
  80. <input type="password" class="form-control rounded-0" name="password" id="password" value="" required>
  81. </div>
  82. <div class="mb-3 text-center">
  83. <div class="col-lg-4 col-md-6 col-sm-10 col-sm-12 mx-auto">
  84. <button class="btn btn-primary rounded-pill">Register</button>
  85. </div>
  86. </div>
  87. </form>
  88. </div>
  89. </div>
  90. </div>
  91. </div>
  92. </div>
  93. </div>
  94. <footer class="shadow-top py-4 col-auto">
  95. <div class="">
  96. <div class="text-center">
  97. All Rights Reserved &copy; <span id="dt-year"></span> | <span class="text-muted">PHP - Password Hashing</span>
  98. </div>
  99. <div class="text-center">
  100. <a href="mailto:[email protected]" class="text-decoration-none text-body-secondary">[email protected]</a>
  101. </div>
  102. </div>
  103. </footer>
  104. </main>
  105. </body>
  106. </html>

Output

simple login and registration

Login

The script below contains the HTML code of the login form page interface and PHP codes for checking or validating the entered user credentials.

login.php

  1. <?php
  2. if($_SERVER['REQUEST_METHOD'] == 'POST'){
  3. include_once("db-connect.php");
  4. extract($_POST);
  5. $sql = "SELECT * FROM `users` where `email` = '{$email}'";
  6. $get = $conn->query($sql);
  7. if($get->num_rows > 0){
  8. $data = $get->fetch_assoc();
  9. $is_verify = password_verify($password, $data['password']);
  10. if($is_verify){
  11. echo "<script> alert('Welcome {$data['name']}!'); location.replace('index.php');</script>";
  12. }else{
  13. echo "<script> alert('Login Failed!.');</script>";
  14. }
  15. }
  16. }
  17. ?>
  18. <!DOCTYPE html>
  19. <html lang="en">
  20. <meta charset="UTF-8">
  21. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  22. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  23. <title>PHP - Password Hashing</title>
  24. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  25. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  26. <link rel="stylesheet" href="assets/css/styles.css">
  27. <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script>
  28. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  29. <script src="assets/js/script.js"></script>
  30.  
  31. </head>
  32. start_loader()
  33. </script>
  34. <main>
  35. <nav class="navbar navbar-expand-lg navbar-dark bg-gradient">
  36. <div class="container">
  37. <a class="navbar-brand" href="./">PHP - Password Hashing</a>
  38. <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
  39. <span class="navbar-toggler-icon"></span>
  40. </button>
  41. <div class="collapse navbar-collapse" id="navbarNav">
  42. <ul class="navbar-nav">
  43. <li class="nav-item">
  44. <a class="nav-link" href="./">Home</a>
  45. </li>
  46. <li class="nav-item">
  47. <a class="nav-link active" aria-current="page" href="login.php">Login</a>
  48. </li>
  49. <li class="nav-item">
  50. <a class="nav-link" href="register.php">Registration</a>
  51. </li>
  52. </ul>
  53. </div>
  54. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  55.  
  56. </div>
  57. </nav>
  58. <div id="main-wrapper">
  59. <div class="container-md px-5 my-3">
  60. <div class="col-lg-7 col-md-8 col-sm-10 col-xs-12 mx-auto">
  61. <div class="card rounded-0 shadow">
  62. <div class="card-header rounded-0">
  63. <div class="card-title"><b>Login</b></div>
  64. </div>
  65. <div class="card-body rounded-0">
  66. <div class="container-fluid">
  67. <form action="" id="register" method="POST">
  68. <div class="mb-3">
  69. <label for="email" class="form-label fw-light">Email</label>
  70. <input type="text" class="form-control rounded-0" name="email" id="email" value="<?= $_POST['email'] ?? "" ?>" required>
  71. </div>
  72. <div class="mb-3">
  73. <label for="password" class="form-label fw-light">Password</label>
  74. <input type="password" class="form-control rounded-0" name="password" id="password" value="" required>
  75. </div>
  76. <div class="mb-3 text-center">
  77. <div class="col-lg-4 col-md-6 col-sm-10 col-sm-12 mx-auto">
  78. <button class="btn btn-primary rounded-pill">Login</button>
  79. </div>
  80. </div>
  81. </form>
  82. </div>
  83. </div>
  84. </div>
  85. </div>
  86. </div>
  87. </div>
  88. <footer class="shadow-top py-4 col-auto">
  89. <div class="">
  90. <div class="text-center">
  91. All Rights Reserved &copy; <span id="dt-year"></span> | <span class="text-muted">PHP - Password Hashing</span>
  92. </div>
  93. <div class="text-center">
  94. <a href="mailto:[email protected]" class="text-decoration-none text-body-secondary">[email protected]</a>
  95. </div>
  96. </div>
  97. </footer>
  98. </main>
  99. </body>
  100. </html>

Output

simple login and registration

DEMO VIDEO

That's it! I have provided also the source code zip that I created for this tutorial on this site and is free to download. Feel free to download it by clicking the download button located below this tutorial's content.

That's the end of this tutorial. I hope this Password Hashing in PHP tutorial will help you with what you are looking for and will be useful for your current and future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Add new comment