3 Methods to Send Forgotten (Reset) Password By Mail in PHP & MySql
31

3 Methods to Send Forgotten (Reset) Password By Mail Using PHP And MySql

Send Forgotten (Reset) Password by mail using PHP and MySql is a simple script to send the password to user email, if the user forgets their password. They will fill in E-mail or username, if the e-mail or username matches in our database value, then the password will be delivered to user email id.

User can reset password using these 3 methods that is

  1. Sending Password fetched from database, if it’s plain text password in database (plain text password is not recommended)
  2. Generating a Random string as password and sending it to user in email (Password will be updated in database with hashed password)
  3. Using Password Reset Token (We will generate a random hashed string, this hashed string will be stored in the database, not in password column. A link will be sent to user through email, after clicking on the link in email user will be prompted to enter the password, Untill this step user always can login with old password.)

This is a continuation for the last two scripts, this script adds the functionality of retrieving forgotten password(Send Forgotten Password by mail using PHP and MySql) with username/email and sending the password through email.

  1. Simple User Registration Script in PHP and MySQL
  2. Simple Login Script in PHP and MySQL
  3. User Login with activation check using PHP and MySQL
  4. Send Forgotten Password by mail using PHP and MySQL
  5. Check Username Availability With jQuery In PHP And MySql

First we will connect to the database, and if the form is submitted, submitted value is assigned to a variable. After that we will fetch the password from database, if the username matches in the database, and if the results count is equal to one, then we will assign the value of password from database to variable, after that we will send the plain text password to user through email.

Below is the Video on PHP User Login Registration Script With All Features

Do you want to Build Secure Members Area for your Website?


I've good News for you! Created a Video Course with 5 Hours of Content to create secure members area section

1. Code to Send Forgotten Password by mail in Plain text using PHP & MySql

If you are following from the previous scripts, then add one field in the database as email, and add an email address in that field.

We will create two pages

  1. connect.php
  2. forgotpassword.php

Create connect.php file

If you are following from previous tutorials, you should have this file. Below code is to connecting database and selecting the database.

Create a Form for Forgot Password

Here we will display only username field, based on the username will fetch the data to send email.

Add styles

Here I’m using Bootstrap to add styling and some custome styles.

Save this below code as styles.css file.

PHP Code to Send Forgotten Password by E-Mail

I’m including connect.php file for connecting to database, add this below line of code before opening HTML tag.

After submitting the form, check if post superglobal is set & not empty, then assign submitted username to variable. Check that username exists in database using the select query, the select query should return one record. We can check it using mysqli_num_rows PHP function. Below is the code.

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

Then add php mail function with to email address, subject line, message and from address. If the mail sent successfully then I’m displaying success message or failure message.

Complete code of forgotpassword.php file

If you have problem arranging above bits of code, here is the complete code you can use.

2. Generating a Random string as password and sending it to user in email

Here you will learn about creating a random string and we will make it as md5 after that we will update the password stored in database with this hashed string.

Here is the code to generate a random string and also making it as a hashed password.

To update the password in database use this update query, so that the password will be updated. Instead of md5 hash, you can use password_hash, it’s more secure method for storing the password in database.

Unlock the below code

If the result is successful you can send the email with plain text password to user, you can use the above code to send email.

3. Using Password Reset Token

This is the best method to reset the password, for this we should create an extra column in the database. We will generate a random string, this string will be stored in database column and we will send this random string to user through email as a link.

User can click on the link, after that we will check that random key in string. If it matches with key in our database, then we will allow user to update the password by showing a password input field.

If users fills new password and submit the form, then only password will be updated. Until user finishes this step, he can always login in with the old password.

This is the recommended way to reset the password and also you can implement cross-site request forgery method to add an extra layer of security to your forms.

If you want to learn other things you can read other posts – registration, login, user login with activation check, and sending forgotten password by email, Check Username Availability .

I hope this article helped you to learn user login using PHP and MySQL . To get latest news and updates follow us on twitter & facebook, subscribe to newsletter. If you have any feedback please let us know by using comment form.

Do you want to Build Secure Members Area for your Website?


I've good News for you! Created a Video Course with 5 Hours of Content to create secure members area section


forgot password code in php forgot password in php Forgot password php forgot password php code php forgot password script forgot password php script forget password code in php php code for forgot password php forgot password email verification ?gander?ttshandlingarna your password will be sent to the email address you enter
Vivek Vengala
 

Vivek Vengala is a Online Entrepreneur, Web Developer from Hyderabad India.

Click Here to Leave a Comment Below 31 comments
Ayisha Raj

http://codingcyber.com/send-forgotten-password-by-mail-using-php-and-mysql-35/#

Thi$ code i$ not \/\/orking…..plea$e $end a $uitable code for the $ame

Reply
    Vivek Vengala

    Hi Ayisha Raj,

    What’s the issue, you are facing? Download entire script and try it on web server.

    Check whether mails are working in your server with simple mail function.

    Reply
silvia

thank you so much its working

Reply
Fadi

Thanks Mate..!!

You Really helped me out ..!!

Reply
akinzben

it really worked tanks for dat bro

Reply
ranjit kumar

why not your forgetpass code is not workig

Reply
    Vivek Vengala

    Hi Ranjith, Thanks for using my code.

    Please try it on web server, it will work. Let me know the feedback.

    Reply
Dennis Briggs

It’s nice that you posted the script forgotpassword.php as a whole. If you uncomment line 13 and 15 it does not show you the email or password. The script just goes blank on post.

Reply
    Vivek Vengala

    Hi Dennis,

    Thanks for letting me know.

    Reply
    Dennis Briggs

    Also if there is no rows in the db it just show a blank page

    Reply
      Vivek Vengala

      Yes Dennis.

      You should follow from User Registration & User Login Script. Otherwise just insert few rows in database.

      Reply
        Dennis Briggs

        I added a row in the db. Row username is somename and pw and marked it active with a 1.
        If you enter a username that is not in the database the script just goes blank.(no checking)

        Reply
          Vivek Vengala

          on line 35 replace the code with this line without quotes “if (empty($to)) {”

          Thanks for pointing the error, I’ll update the code soon.

          Reply
Dennis Briggs

In ASP Script mine look like this
mySQL = “SELECT * FROM table WHERE email = ‘” & strEmail & “‘”

Set objRS = Server.CreateObject(“ADODB.Recordset”)
objRS.Open mySQL, StrCon

IF objRS.EOF THEN
Response.Write “That email address was not found in our database. Please click Back on your browser and enter the email address you registered with.”
ELSE

Reply
Dennis Briggs

This script is very nice on line 14 I added
echo “”; just for looks when checking scipt.
on line 16 I added
$email = $rows[’email’];//FETCHING EMAIL
So the script will echo the email on line 17

Reply
    Vivek Vengala

    Thats Great Dennis,

    Don’t forget to subscribe E-mail Newsletter, Like us on Facebook

    If you want to any other PHP scripts, let me know through the Contact Us page. I’ll do my best.

    Reply
Nitesh

Warning: mail(): SMTP server response: 503 Bad sequence of commands. in C:\xampp\htdocs\quiz\login.php on line 42

Reply
    Vivek Vengala

    Hi Nitesh,

    Use this code in web server, So that emails will be delivered.

    If you are localhost, you can use phpmailer with smtp email server also will work.

    Reply
      Nitesh

      Hey thanks I got.

      Reply
ahmed

Why did you put
}else{
if ($_POST [’email’] != “”) {
$fmsg = “Not found your email in our database”;
}
}
I think you can just make it like that
}else{
echo “Not found your email in our database”;
}
==================================================
also
//If the message is sent successfully, display sucess message otherwise display an error message.
if($sentmail==1)
{
$smsg = “Your Password Has Been Sent To Your Email Address.”;
}
else
{
if($_POST[’email’]!=””)
$nmsg = “Cannot send password to your e-mail address.Problem with sending mail…”;
}
}

I think you can do it like that
if($sentmail==1)
{
echo “Your Password Has Been Sent To Your Email Address.”;
}
else{
echo “Cannot send password to your e-mail address.Problem with sending mail…”;
}

Reply
    Vivek Vengala

    Hello Ahmed,

    You can do that, but I’m displaying these messages inside body section.
    So that’s why I’m assigning these messages to variables.

    Reply
Rajeev Singh

Hiiii Vivek…

I have created registered and login page successfully. But, when I run this forgot password script in our localhost. Its not working. I am using Ubuntu

Please, reply me soon and let me know what to do

Reply
    Vivek Vengala

    Hello Rajeev,

    You need to install Mail Server, if you don’t know you can use any smtp server with PHPMailer.

    You can learn from here How to Use PHP Mailer – Easy Way

    Reply
Max

Hi, can I know how to display the username and password of the user based on the email?

Reply
    Vivek Vengala

    Hello Max,

    Fetch information from the database using SELECT query, display it using echo PHP function.

    Reply
nez

if connect.php contain connection script, then what is inside config.php?

Reply
    Vivek Vengala

    I’m using config for smtp login credentials.

    Reply
      nez

      could you please give full example? can’t find config.php’s content at your article 🙁

      Reply
Moses

Vivek Vengala,
you are a talented instructor….

thanks a lot bro

Reply
prathamesh govekar

i want to see video of send forgot password

Reply
    Vivek Vengala

    Thank you prathamesh for your request, I’ll create a video for forgot password also.

    Reply

Leave a Reply: