Sample PHP code for creating forgot password feature in any website

Most of the websites will require the users to register them for getting username/password which can be used for logging into their website.

It is very common that the users forget their password. So, the websites should allow the users to receive their password into their email using forgot password link available in the login page.

Find below the sample php code which can be used for implementing the forgot password feature.


if ($email_to == “”) // Email address cannot be empty
header(“Location: mail-password.php?send=Email not entered”);
if(is_valid_email($email_to)) // check the valid email address or not
$subject=”QualityPoint Password”; // Your subject
// From
$header = ‘From:’ . “\r\n” .
‘Reply-To:’ . “\r\n” .
‘X-Mailer: PHP/’ . phpversion();
//add code for selecting $userid and $pass for user table for the input $email_to.
// Your message
$messages.=”Forgot password – \r\n”;
$messages.=”————————————– \r\n”;
$messages.= “Your login information to our website is- \r\n”;
$messages.=”UserId: $userid \r\n”;
$messages.=”Password: $pass \r\n”;
$messages.=”————————————– \r\n”;

// send email
$sentmail = mail($to,$subject,$messages,$header);

if($sentmail) //if your email succesfully sent
header(“Location: mail-password.php?send=Password has been sent to your email id”);
else // Cannot send password to your e-mail address
header(“Location: mail-password.php?send=Not able to send email”);

else //Email address has not been found in our database
header(“Location: mail-password.php?send=Email address not found”);

function is_valid_email( $address )
$rx = “^[a-z0-9\\_\\.\\-]+\\@[a-z0-9\\-]+\\.[a-z0-9\\_\\.\\-]+\\.?[a-z]{1,4}$”;
return (preg_match(“~”.$rx.”~i”, $address));

The step involved are,
1. First provide a form with input text box with name “email” for allowing the user to enter his email id.

2. On submitting this form, the “email” will be posted to the php page mail-password.php.

3. From user table, query the password corresponding to the entered email id. (If you have stored the password in encrypted form then reset it with default/random password and send this default/random password to the user)

4. Validate the email id.

5. Prepare the email message and send it using php mail() function.

Posted in MySQL, Php Tagged with: ,