Php

How To Reset Password by Email Using PHP7 and MySQLi

You will learn How to recover/reset a forgotten password using PHP and MySQLi in this post. We’ll show you how to use a Forgot Password form to recover your password if you’ve forgotten your username or email. We’ll send a password recovery email to the user after the form is submitted.

There are several accounts on various websites and platforms. The majority of individuals forget their passwords and attempt to reset their passwords on the website.

In this post, You’ll learn how to use PHP and MySQLi to retrieve a forgotten password.

Recover Forgot Password By Email Using PHP7 and MySQLi

We will create a forgot password HTML form using bootstrap 4. There are three fields in this file: username, new password, and confirm the new password, as well as a Submit button. This form is forwarded to the forgot.php page after the user submits the form.

Assume the database contains a 'users' TABLE with one user entry, as shown below. If you have a database, you can use it.

CREATE TABLE IF NOT EXISTS `users` (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `username` varchar(100) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(100) NOT NULL,
  PRIMARY KEY (`userid`)
)
INSERT INTO `users` (`userid`, `name`, `username`, `password`) VALUES
(1, 'test', 'test abc', 'guy76tvt577vvtyyunmkl990mnn76668');

Connect MySQL Database with PHP Using mysqli_connect() :

Let’s create a connect.php file to connect MySQL database with PHP. The below code is to connecting database and selecting the database.

<?php
$connection = mysqli_connect('localhost', 'root', 'paasword');
if (!$connection){
    die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'test');
if (!$select_db){
    die("Database Selection Failed" . mysqli_error($connection));
}

Create a Form for Forgot Password

Created a forgot.php file into the PHP project. We have started the session at the top of the file. Let’s add the HTML code that shows the forgot password form –

Related Post
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

<form id="register-form" role="form" autocomplete="off" class="form" method="post">    
  <div class="form-group">
 <div class="input-group">
   <span class="input-group-addon"><i class="glyphicon glyphicon-envelope color-blue"></i></span>
   <input id="email" name="email" placeholder="email address" class="form-control"  type="email">
 </div>
  </div>
  <div class="form-group">
 <input name="recover-submit" class="btn btn-lg btn-primary btn-block" value="Reset Password" type="submit">
  </div>
  
  <input type="hidden" class="hide" name="token" id="token" value=""> 
</form>

In the code above, we have created one email field into the form. The user will enter the registered email id and ll receive an email once the emailid is correct.

PHP Code to Send Forgotten Password by E-Mail

Once this forgot password form is submitted, the entered data is sent in the post to the 'handler.php' file.Let’s create a handler.php php script that will get form data is POST method.

if(isset($_POST) & !empty($_POST)){
 $email = mysqli_real_escape_string($connection, $_POST['email']);
 $sql = "SELECT * FROM `login` WHERE email = '$email'";
 $res = mysqli_query($connection, $sql);
 $count = mysqli_num_rows($res);
 if($count == 1){
  echo "Send email to user with password";
 }else{
  echo "User name does not exist in database";
 }
}

in the above code, The First check the POST superglobal is set & not empty and assign the submitted emailid to a variable. Check that username exists in the database using the select query.

If the mysqli_num_rows() PHP function returns one row, then we will send an email with a plain text password that is fetched from the database using the select query. Assign values of email, password to variables fetched from the select query.

Send Email Using PHP

Let’s create a PHP logic that will send mail using PHPMailer class.

$r = mysqli_fetch_assoc($res);
   $password = $r['password'];
   $to = $r['email'];
   $subject = "Your Recovered Password";
 
   $message = "Please use this password to login " . $password;
   $headers = "From : vivek@codingcyber.com";
   if(mail($to, $subject, $message, $headers)){
      echo "Your Password has been sent to your email id";
   }else{
     echo "Failed to Recover your password, try again";
}
  }

Full PHP Source

The full source code for recover password by email.

<?php
require_once('connect.php');
require('config.php');
require('PHPMailer/PHPMailerAutoload.php');
if(isset($_POST) & !empty($_POST)){
 $email = mysqli_real_escape_string($connection, $_POST['email']);
 $sql = "SELECT * FROM `login` WHERE email = '$email'";
 $res = mysqli_query($connection, $sql);
 $count = mysqli_num_rows($res);
 if($count == 1){
  $r = mysqli_fetch_assoc($res);
  $password = $r['password'];
  $to = $r['email'];
  $subject = "Your Recovered Password";

  $message = "Please use this password to login " . $password;
  $headers = "From : admin@phpflow.com";
  if(mail($to, $subject, $message, $headers)){
   echo "Your Password has been sent to your email id";
  }else{
   echo "Failed to Recover your password, try again";
  }

 }else{
  echo "Email does not exist in database";
 }
}


?>
<!DOCTYPE html>
<html>
<head>
 <title>Forgot Password in PHP & MySQL</title>
 <!-- Latest compiled and minified CSS -->
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
</head>
<body>
<div class="container">
      <?php if(isset($smsg)){ ?><div class="alert alert-success" role="alert"> <?php echo $smsg; ?> </div><?php } ?>
      <?php if(isset($fmsg)){ ?><div class="alert alert-danger" role="alert"> <?php echo $fmsg; ?> </div><?php } ?>
        <form id="register-form" role="form" autocomplete="off" class="form" method="post">    
    <div class="form-group">
   <div class="input-group">
     <span class="input-group-addon"><i class="glyphicon glyphicon-envelope color-blue"></i></span>
     <input id="email" name="email" placeholder="email address" class="form-control"  type="email">
   </div>
    </div>
    <div class="form-group">
   <input name="recover-submit" class="btn btn-lg btn-primary btn-block" value="Reset Password" type="submit">
    </div>
    
    <input type="hidden" class="hide" name="token" id="token" value=""> 
  </form>
</div>
</body>
</html>

Conclusion:

We have connected the MySQLi database with PHP using mysqli_connect() method. We have also created forgot password form using bootstrap 4.Also send forgot email using PHP mailer.

Tags: php 7

View Comments

Recent Posts

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

2 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

2 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

2 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

3 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

3 months ago

Common Practices for Laravel Blade Template

in this Laravel tutorial, I will explore common practices for using the Laravel Blade template with examples. Blade is a… Read More

3 months ago

Categories