You are here:Home » PHP » PHP Forgot Password Tutorial

PHP Forgot Password Tutorial

Forgot Password
This tutorial is about building a forgot password system(Password Resetting System) with PHP when password is encrypted with MD5() ,SHA1() or any other encryption algorithm .
When you are storing the passwords of users in plain text then you can easily send their password to their email id.But in case of encrypted password  it is not possible to send the plain password to the users because you can not decrypt these passwords.
Basically there are two ways to reset the passwords.First one is assign a random password to the user and send to their email id,but this method can be misused by other users .For example any member can reset other member’s password if he knows email id.So i will not recommend two use this method.Second method is instead of changing the password , assign a random token for that user when he request for password reset.Store this token into your database and also send this token to user’s email id.The best way to send the token is in form of a link .See the link below…
<a href=âhttp://yourwebsite.com/reset.php?token=RANDOM_TOKENâ>Reset Password </a>
When user will click on this link you will can easily determine that which user wants to change the password after getting value of token by $_GET['token'] and compare this value to all available tokens.Now start a session and ask  for new password to your user and store the password in encrypted format in your database.After successful password reset either delete the token or mark that token as used .
If you understand the above method of resetting password then its time code the PHP script.Here is step by step guide to build your own Forgot Password PHP Script.
1).Build tables and database-At first you need to create a file which includes settings for your database to connect.The code is given below ,you just need to change values of all variables.Now open PHPMyAdmin and import the sql file available in attachment or manually create a table name “token” containing three fields email ,password and used.
<?php
//file name: settings.php
//Title:Build your own Forgot Password PHP Script
function connect()
{	
$host="localhost"; //host
$uname="root";  //username
$pass="";      //password
$db= 'test';  //database name

$con = mysql_connect($host,$uname,$pass);

if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db($db, $con);}
2).Password reset form-Build a simple form using HTML which ask for email id of user.You may use CAPTCHA for better security.I am doing this without CAPTCHA so here is the code .
<?php
//file name: forgotpassword.php 
//Title:Build your own Forgot Password PHP Script
echo'<form action="forgotpassword.php">
	Enter Your Email Id:
	<input type="text" name="email" />
	<input type="submit" value="Reset My Password" />
	</form>';
3).Assign a token and mail it-After getting email id of user first check that email id exist in your database or not.If email id exist then assign a random token ,store the token in a table say “token” with user’s email id and send a password reset link to the user.
<?php
//file name: forgotpassword.php
//Title:Build your own Forgot Password PHP Script
if(!isset($_GET['email'])){
	                  echo'<form action="forgotpassword.php">
	                      Enter Your Email Id:
	                         <input type="text" name="email" />
	                        <input type="submit" value="Reset My Password" />
	                         </form>'; exit();
				       }
$email=$_GET['email'];
include("settings.php");
connect();
$q="select email from users where email='".$email."'";
$r=mysql_query($q);
$n=mysql_num_rows($r);
if($n==0){echo "Email id is not registered";die();}
$token=getRandomString(10);
$q="insert into tokens (token,email) values ('".$token."','".$email."')";
mysql_query($q);
function getRandomString($length) 
	   {
    $validCharacters = "ABCDEFGHIJKLMNPQRSTUXYVWZ123456789";
    $validCharNumber = strlen($validCharacters);
    $result = "";

    for ($i = 0; $i < $length; $i++) {
        $index = mt_rand(0, $validCharNumber - 1);
        $result .= $validCharacters[$index];
    }
	return $result;}
 function mailresetlink($to,$token){
$subject = "Forgot Password on Megarush.net";
$uri = 'http://'. $_SERVER['HTTP_HOST'] ;
$message = '
<html>
<head>
<title>Forgot Password For Megarush.net</title>
</head>
<body>
<p>Click on the given link to reset your password <a href="'.$uri.'/reset.php?token='.$token.'">Reset Password</a></p>

</body>
</html>
';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: Admin<webmaster@example.com>' . "\r\n";
$headers .= 'Cc: Admin@example.com' . "\r\n";

if(mail($to,$subject,$message,$headers)){
	echo "We have sent the password reset link to your  email id <b>".$to."</b>"; 
}}

if(isset($_GET['email']))mailresetlink($email,$token);
4.)Change the password-When user clicks on password reset link ,first check if it is valid or not.If it is valid then start a session and ask for new password.
<?php
//file reset.php
//title:Build your own Forgot Password PHP Script
session_start();
$token=$_GET['token'];
include("settings.php");
connect();
if(!isset($_POST['password'])){
$q="select email from tokens where token='".$token."' and used=0";
$r=mysql_query($q);
while($row=mysql_fetch_array($r))
   {
$email=$row['email'];
   }
If ($email!=''){
          $_SESSION['email']=$email;
}
else die("Invalid link or Password already changed");}
$pass=$_POST['password'];
$email=$_SESSION['email'];
if(!isset($pass)){
echo '<form method="post">
enter your new password:<input type="password" name="password" />
<input type="submit" value="Change Password">
</form>
';}
if(isset($_POST['password'])&&isset($_SESSION['email']))
{
$q="update users set password='".md5($pass)."' where email='".$email."'";
$r=mysql_query($q);
if($r)mysql_query("update tokens set used=1 where token='".$token."'");echo "Your password is changed successfully";
if(!$r)echo "An error occurred";
	}

24 comments:

  1. It sends the email, but the reset link does not work, when I click, it don't do anything........ Any idea?

    ReplyDelete

  2. Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\Myconnec\reset.php on line 50
    Invalid link or Password already changed

    ReplyDelete
  3. dude help out here something is wrong..

    ReplyDelete
  4. Great php tutorials tips for programming. It can help better for php developers.Thanks for this useful post.

    ReplyDelete
  5. The Email will only sent when you are using server not local right?

    ReplyDelete
    Replies
    1. i already tried it in local and server but i didnt recieve an message on my gmail and yahoo.

      Delete
    2. and also i already created username,password an email any idea why i dont recieve?

      Delete
  6. Below is a listing of all models of Rolex Replica Watches available from Swiss Rolex Watches. Please select the model of Replica Rolex Watches below in order to few all available combinations. All Replica Hermes Handbags prices listed below include free shipping via EMS worldwide where available. If you have further questions about any of the Replica Louis Vuitton Handbags featured on this website, please contact us.

    ReplyDelete
  7. Thats Really Amazing....Post
    So helpfull.....

    ReplyDelete
  8. I have entered the code above and ironed out the bugs that stopped it from working. If anyone is interested in the code please reply and I will post it.

    ReplyDelete
    Replies
    1. Hi there, can you send me the working code, i cant find the bugs. Many thanks

      Delete
  9. Thanku so much for the help its Amazing

    ReplyDelete
  10. Thanku so much for the help its Amazing

    ReplyDelete
  11. Thanku so much for the help its Amazing

    ReplyDelete
  12. I'm getting this error when i click on the Email link to reset the password.

    Invalid link or Password already changed

    ReplyDelete
    Replies
    1. Im now getting the Text box but when i change the password, i just get a blank screen, i don't get a Successful Text Result appear on the screen.

      Delete
    2. I don't even get an Error Message on the screen.

      Delete
  13. Iam getting mail but when i click on reset password link there is a
    Error undefined variable email.
    How u declare the var email.

    ReplyDelete
  14. nice tutorials bro post is good and more php info in Hindi main concepts visit my friend blog www.gajabwap.blogspot.in

    ReplyDelete
  15. Superb, what a weblog it is! This website presents helpful information to us, keep it up -
    Recover forgot password using PHP and MySQL

    ReplyDelete