Web Design and Programming Pt 23

PHP Forgot Password ScriptIn this web design and programming video tutorial I’ll show you how to make a secure forgotten password script. These scripts are attacked more than mosts and normally are full of security flaws.

I specifically cover how to:

  • Strip dangerous code from user input using Regular Expressions
  • Enforce secure security questions
  • Avoid brute force attacks with CAPTCHA systems
  • Create secure encrypted temporary passwords
  • Mail new passwords

All of the code used will follow the video. If you have any questions or comments leave them below.

If you have a recommendation for a future tutorial leave that below as well 🙂

Code From the Video

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″ />
<title>Forgot My Password</title>
<div id=”main”>
if (isset($_POST[‘submitted’])) { // Handle the form.
// Check for a valid User ID
if (preg_match (‘%^[A-Za-z0-9]{8,20}$%’, stripslashes(trim($_POST[‘userid’])))) {
$u = escape_data($_POST[‘userid’]);
} else {
$u = FALSE;
echo ‘<p><font color=”red” size=”+1″>1Information Entered is Wrong</font></p>’;
// Check for valid Mother name
if (preg_match (‘%^[A-Za-z]{6,25}$%’, stripslashes(trim($_POST[‘mothername’])))) {
$sq = escape_data($_POST[‘mothername’]);
} else {
$sq = FALSE;
echo ‘<p><font color=”red” size=”+1″>2Information Entered is Wrong</font></p>’;
// PHP Code for the CAPTCHA System
$captchchk = 1;
$privatekey = “privatekey”;
$resp = recaptcha_check_answer ($privatekey,
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
echo ‘<p><font color=”red” size=”+1″>The CAPTCHA Code wasn\’t entered correctly!</font></p>’;
$captchchk = 0;
if ($u && $sq && $captchchk) {
// Check the account information
$query = “SELECT secques, email, userid FROM users WHERE userid=’$u'”;
$result = mysql_query ($query) or trigger_error(“Security Answer was Wrong”);
if (mysql_affected_rows() == 1) {
$row = mysql_fetch_array ($result, MYSQL_NUM);
if($sq == $row[0])
$email = $row[1];
$p = substr ( md5(uniqid(rand(),1)), 3, 10);
$query2 = “UPDATE users SET pass=SHA(‘$p’) WHERE userid=’$u'”;
$result2 = mysql_query ($query2) or trigger_error(“Your Password Couldn’t be changed. Try later.”);
if (mysql_affected_rows() == 1) { // If it ran OK.
$body = “Your password has been temporarily changed to ‘$p’. Please log in using this password and your username. At that time you may change your password to something more familiar.”;
mail ($email, ‘Your temporary password.’, $body, ‘From: admin@sitename.com’);
echo ‘<h3>Your password has been changed. You will receive the new, temporary password at the email address with which you registered. Once you have logged in with this password, you may change it by clicking on the “Change Password” link.</h3>’;
else {
echo “Security Answer was Wrong”;
} else { // If it did not run OK.
echo ‘<p><font color=”red” size=”+1″>Your password could not be changed due to a system error. We apologize for any inconvenience.</font></p>’;
} else { // Failed the validation test.
echo ‘<p><font color=”red” size=”+1″>Please try again.</font></p>’;
}} // End of the main Submit conditional.
<h1>Reset Your Password</h1>
<p>Enter the Following Information Below and your Password will be Reset.</p>
<form action=”forgot_password.php” method=”post”>
<p><b>Userid:</b> <input type=”text” name=”userid” size=”20″ maxlength=”20″/></p>
<p><b>Mothers or Grandmothers Maiden Name:</b> <input type=”text” name=”mothername” size=”25″ maxlength=”25″/></p>
$publickey = “publickey”; // you got this from the signup page
echo recaptcha_get_html($publickey);
<div align=”center”><input type=”submit” name=”submit” value=”Reset My Password” /></div>
<input type=”hidden” name=”submitted” value=”TRUE” />

11 Responses to “Web Design and Programming Pt 23”

  1. Mustix says:

    Hello derek
    I have got a problem with this code.
    I have tryed this code you gave And i also used this:
    username, \n\n you or someone else have requested your account details. \n\n Here is your account information please keep this as you may need this at a later stage. \n\nYour username is $r->username \n\n your password is $password \n\n Your password has been reset please login and change your password to something more rememberable.\n\n Regards Site Admin”;
    $additionalheaders = “From: \r\n”;
    $additionalheaders .= “Reply-To: noprely@domain.com“;
    mail($to, $subject, $body, $additionalheaders);

    //update database
    $sql = mysql_query(“UPDATE users SET userpass=’$pass’ WHERE mail = ‘$email'”)or die (mysql_error());
    $rsent = true;

    } // close errors
    } // close if form sent

    //show any errors
    if (!empty($error))
    $i = 0;
    while ($i < count($error)){
    echo "”.$error[$i].””;
    $i ++;}
    }// close if empty errors

    if ($rsent == true){
    echo “You have been sent an email with your account details to $email\n”;
    } else {
    echo “Please enter your e-mail address. You will receive a new password via e-mail.\n”;


    Email Address:

    The problem is it doesn’t send me anything to my e-mail.
    Can you help me.
    And i’m waiting for u chat tutorial.
    Thanks in advance.

  2. Mustix says:

    Sorry the whole code won’t be displayed

    • admin says:

      I sent you the original code by email. It is tested and will work. WordPress messes up code some times when I post it. Sorry about that

  3. Mustix says:

    Can you give me one without Captcha .
    Because the whole problem is in the mail function.
    It says We have sent a mail with you new password.
    The query update the password but there is now Mail recieved.
    Can you help me.
    Thanks in advance

    • admin says:

      Here is where you can get a captcha key http://www.google.com/recaptcha

      It’s free and only takes a few seconds to get a public and private key. Believe me you want this or your account will be overrun with spammers. Also make sure you entered your email in the script and you should be fine.

  4. admin says:

    No don’t give me that. Ok, so the database is updating but the email isn’t being sent right?

    If that is so, you probably have to set up email in your php.ini file. Is that the problem you’re having?

  5. Mustix says:

    Yes the first you are right
    The second it is already actived.

  6. dnabbrocks says:

    Hi. Does this mean we all need you to email us the correct script?

    • admin says:

      No the code under the video works. You just have to replace the backquotes with regular quotes. A quick find and replace and you are ready to go. Sorry, my older tutorials had this security feature

  7. Martin says:

    I am having problem with receiving the new password on my email,
    pls any suggestion as to how to fix this? I can email you my code on request.


Leave a Reply

Your email address will not be published.