Skip to content
No results
  • Home
  • Blog
  • Tutorials
    • Mysql
    • PHP
    • PHP OOP
    • API
    • Jquery
    • Ajax
    • Javascript
    • JSON
    • Bootstrap
    • WordPress
  • Framework
    • Laravel 9
    • CakePHP 4
    • Codeingniter
  • Payment Gateway
  • Tools
    • Try Online Editor
  • Live Demo

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.

  • Home
  • About us
  • Privacy Policy
  • Terms & Conditions
  • Contact us
  • Disclaimer
  • Sitemap
Facebook Twitter Instagram LinkedIn Medium Pinterest
Webs Codex
  • Home
  • Blog
  • Tutorials
    • Mysql
    • PHP
    • PHP OOP
    • API
    • Jquery
    • Ajax
    • Javascript
    • JSON
    • Bootstrap
    • WordPress
  • Framework
    • Laravel 9
    • CakePHP 4
    • Codeingniter
  • Payment Gateway
  • Tools
    • Try Online Editor
  • Live Demo
Webs Codex
Home Mysql PHP Login Registration Script by using Password_hash() & Password verify() method for Secure login

PHP Login Registration Script by using Password_hash() & Password verify() method for Secure login

  • ManishManish
  • August 1, 2020
  • Mysql, PHP
PHP Login Registration Script by using Password_hash() & Password verify() method for Secure login

If you are looking for ways to use the password_hash() method to log in and register in a PHP script. In this tutorial we will discuss how to use the PHP password hash method to secure logins and registrations. This PHP password_hash() method creates a new password hash using an efficient one-way hashing algorithm.

This method was first introduced in PHP 5.5 and creates a new password hash with a length of 60 characters. We store this hash password in our database. It is very difficult to hack and can be verified using a password verification method. If you are building an application and want to implement a strong login for your application, you can use this password_hash() method for a strong registration for your application.

When we register with this type of registration, the password is hashed with the password_hash() method and stored in the database. When we log in, this type of hash password can be confirmed using the password_verify() method. 

This is a complete system to exit the registration system using the password_hash() method. If a new user enters this type of system, this system generates a password hash from the password he entered when logging in with the password_hash() method.

This method produces 60 characters with a password hash using the password hashing algorithm. After we save this hash password in the database and the user enters, enter your password with this user after confirmation. Because the user has entered a password with a password hash using the password_verify() method, this method checks this Password hash with a normal password string.

See also  How to Check username & email already exists using jquery ajax in PHP mysql

If the two passwords match, true is returned to indicate the password match. However, if you adopt this method again incorrectly means that the passwords do not match. This is the best way to prevent password hacking.

Table of Contents

  • Create MySql Connection in PHP
  • Create Registration HTML Form and PHP Code
  • Create Login HTML Form and PHP Code
  • Create User Profile Page after Login Successful
  • Create Logout Page

Create MySql Connection in PHP

For importing and exporting database in MySql will make a separate file ‘config.php’. Add the following code and replace the database credentials with yours. You can find your db credentials in Application Access details:

<?php
	// Database configuration 
	$dbHost     = "localhost"; 
	$dbUsername = "root"; 
	$dbPassword = ""; 
	$dbName     = "registration"; 
	 
	// Create database connection 
	$con =  new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); 
	 
	// Check connection 
	if ($con->connect_error) { 
	    die("Connection failed: " . $con->connect_error); 
	} 
?>

Create Registration HTML Form and PHP Code

index.php

<?php
  
  // Include database connectivity
      
  include_once('config.php');
  
  if (isset($_POST['submit'])) {
      
      $errorMsg = "";
      
      $fullname = mysqli_real_escape_string($con, $_POST['fullname']);
      $username = mysqli_real_escape_string($con, $_POST['username']);
      $email    = mysqli_real_escape_string($con, $_POST['email']);
      $password = mysqli_real_escape_string($con, $_POST['password']);
      $password = password_hash($password, PASSWORD_DEFAULT);
      
      $sql = "SELECT * FROM students WHERE email = '$email'";
      $execute = mysqli_query($con, $sql);
        
      if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          $errorMsg = "Email in not valid try again";
      }else if(strlen($password) < 6) {
          $errorMsg  = "Password should be six digits";
      }else if($execute->num_rows == 1){
          $errorMsg = "This Email is already exists";
      }else{
          $query= "INSERT INTO students(fullname,username,email,password) 
                  VALUES('$fullname','$username','$email','$password')";
          $result = mysqli_query($con, $query);
      if ($result == true) {
          header("Location:login.php");
      }else{
          $errorMsg  = "You are not Registred..Please Try again";
      }
    }
  }

?>
<!Doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>PHP Password hash Registration in PHP Mysql</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="margin-top:50px">
<h1 style="text-align:center;">PHP Password_hash Registration in PHP Mysql</h1><br>
  <div class="row">
    <div class="col-md-4"></div>
      <div class="col-md-4">
        <?php
            if (isset($errorMsg)) {
                echo "<div class='alert alert-danger alert-dismissible'>
                        <button type='button' class='close' data-dismiss='alert'>&times;</button>
                        $errorMsg
                      </div>";
            }
        ?>
        <form action="" method="POST">
          <div class="form-group">
             <input type="text" class="form-control" name="fullname" placeholder="Full Name" required="">
          </div>
          <div class="form-group">
             <input type="text" class="form-control" name="username" placeholder="Username" required="">
          </div>
          <div class="form-group">
             <input type="email" class="form-control" name="email" placeholder="Email" required="">
          </div>
          <div class="form-group">
             <input type="password" class="form-control" name="password" placeholder="Password" required="">
          </div>
          <p>If you have account <a href="login.php">Login</a></p>
          <input type="submit" class="btn btn-warning btn btn-block" name="submit" value="Sign Up">  
        </form>
      </div>
    </div>
  </div>
</body>
</html>

Registration Output

See also  How to Created PHP CRUD using OOPS with MYSQLi in MVC
PHP Login Registration Script by using Password_hash() & Password verify() method for Secure login

Create Login HTML Form and PHP Code

login.php

<?php
  session_start();

  if (isset($_SESSION['id'])) {
      header("Location:profile.php");
  }

  // Include database connectivity
    
  include_once('config.php');
  
  if (isset($_POST['submit'])) {

      $errorMsg = "";

      $email    = mysqli_real_escape_string($con, $_POST['email']);
      $password = mysqli_real_escape_string($con, $_POST['password']); 
      
  if (!empty($email) || !empty($password)) {
        $query  = "SELECT * FROM students WHERE email = '$email'";
        $result = mysqli_query($con, $query);
        if(mysqli_num_rows($result) == 1){
          while ($row = mysqli_fetch_assoc($result)) {
            if (password_verify($password, $row['password'])) {
                $_SESSION['id'] = $row['id'];
                $_SESSION['fullname'] = $row['fullname'];
                header("Location:profile.php");
            }else{
                $errorMsg = "Email or Password is invalid";
            }    
          }
        }else{
          $errorMsg = "No user found on this email";
        } 
    }else{
      $errorMsg = "Email and Password is required";
    }
  }

?>

<!Doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>PHP Password hash Login in PHP Mysql</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="margin-top:50px">
<h1 style="text-align: center;">PHP Password_hash Login in PHP Mysql</h1><br>
  <div class="row">
     <div class="col-md-4"></div>
      <div class="col-md-4" style="margin-top:20px">
        <?php
            if (isset($errorMsg)) {
                echo "<div class='alert alert-danger alert-dismissible'>
                        <button type='button' class='close' data-dismiss='alert'>&times;</button>
                        $errorMsg
                      </div>";
            }
        ?>
        <form action="" method="POST">
          <div class="form-group">
            <input type="email" class="form-control" name="email" placeholder="Email">
          </div>
          <div class="form-group">
            <input type="password" class="form-control" name="password" placeholder="Password">
          </div>
          <p>Are you new user? <a href="index.php">Sign Up</a></p>
          <input type="submit" class="btn btn-warning btn btn-block" name="submit" value="Login">
        </form>
      </div>
    </div>
  </div>
</body>
</html>

Login Output

PHP Login Registration Script by using Password_hash() & Password verify() method for Secure login

Create User Profile Page after Login Successful

profile.php

<?php
  session_start();
  if (!isset($_SESSION['id'])) {
      header("Location:login.php");
  }
?>
<!Doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>User Profile Page</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
  <div class="container" style="margin-top:50px">
    <h1 style="text-align:center;">User Profile Page</h1><br>
    <div class="row">
       <h5>Hello, <?php echo ucwords($_SESSION['fullname']); ?> <small><a href="logout.php">Logout</a></small></h5>   
    </div>
  </div>
</body>
</html>

Create Logout Page

logout.php

<?php
	include_once('config.php');
	session_start();
	session_destroy();
	session_unset($_SESSION['id']);
	session_unset($_SESSION['fullname']);
	header("Location:login.php");
?>

You can always support by sharing on social media or recommending my blog to your friends and colleagues. If you have any suggestions / problems about this tutorial, please comment on the  form below.😊

# LOGIN# MYSQL# PHP
Previous Post How to Upload Image in database using jQuery AJAX in PHP Mysql
Next Post PHP Login Script with Remember Me using Cookies

Related Blog Posts

How to Send Bulk Emails in PHP using PHPMailer with Ajax jQuery

How to Created PHP CRUD using OOPS with MYSQLi in MVC

Generate PDF File From MySQL Database Using PHP

Leave a ReplyCancel Reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Razorpay Payment Gateway Integration in PHP
  • Paytm Payment Gateway Integration in PHP Step by Step
  • How to Export excel data from Database in PHP using Spreadsheet
  • Import Excel File into MySQL Database in PHP using Spreadsheet
  • What is an API? What is an API integration ?

Follow on Facebook

Tutorial Categories

  • Ajax (38)
  • API (1)
  • CakePHP 4 (6)
  • How To (15)
  • Javascript (1)
  • Jquery (42)
  • JSON (2)
  • Mysql (44)
  • Payment Gateway (2)
  • PHP (56)
  • PHP OOP (7)

Follow on Social

Facebook Twitter Instagram LinkedIn Pinterest Medium

Trending now

How to Send Bulk Emails in PHP using PHPMailer with Ajax jQuery
How to Created PHP CRUD using OOPS with MYSQLi in MVC
Generate PDF File From MySQL Database Using PHP
Registration & Login with Email OTP verification using Jquery AJAX with PHP Mysql

About Webs codex

Webs Codex is a free online resource on programming and web development for beginners to advance. It was founded in Jan 2020 by Manish Pushpakar to deliver the best and fresh articles for students and our readers to skill up as they would like to. we are share multiple technologies tutorials.

Customer Area

  • About us
  • Disclaimer
  • Contact us
  • Privacy Policy
  • Terms & Conditions
  • About us
  • Disclaimer
  • Contact us
  • Privacy Policy
  • Terms & Conditions

Quick Links

  • How To
  • Live Demo
  • Github Code
  • Interview Questions
  • Try Online Editor
  • How To
  • Live Demo
  • Github Code
  • Interview Questions
  • Try Online Editor

Copyright © 2020-22 Webscodex.com All rights reserved