Forgot password script

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • matheussousuke
    New Member
    • Sep 2009
    • 249

    Forgot password script

    I'm currently working on a script, it's a forgot password script, it recognize the user email when you type it correctly in the input field (so it find the email on the database), generate a random password and send it to the user email, until there, everything works fine, but the script is not changing the password in the database.

    Code:
    <?
    define('IN_SCRIPT', true);
    // Start a session
    session_start();
    
    //Connect to the MySQL Database
    include 'includes/application_top.php';
    
    //this function will display error messages in alert boxes, used for login forms so if a field is invalid it will still keep the info
    //use error('foobar');
    function error($msg) {
        ?>
        <html>
        <head>
        <script language="JavaScript">
        <!--
            alert("<?=$msg?>");
            history.back();
        //-->
        </script>
        </head>
        <body>
        </body>
        </html>
        <?
        exit;
    }
    
    //This functions checks and makes sure the email address that is being added to database is valid in format. 
    function check_email_address($email) {
      // First, we check that there's one @ symbol, and that the lengths are right
      if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
        // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
        return false;
      }
      // Split it into sections to make life easier
      $email_array = explode("@", $email);
      $local_array = explode(".", $email_array[0]);
      for ($i = 0; $i < sizeof($local_array); $i++) {
         if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
          return false;
        }
      }  
      
      
      $soea='STORE_OWNER_EMAIL_ADDRESS';
      
      
      if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
        $domain_array = explode(".", $email_array[1]);
        if (sizeof($domain_array) < 2) {
            return false; // Not enough parts to domain
        }
        for ($i = 0; $i < sizeof($domain_array); $i++) {
          if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
            return false;
          }
        }
      }
      return true;
    }
    
    
    if (isset($_POST['submit'])) {
    	
    	if ($_POST['forgotpassword']=='') {
    		error('Please Fill in Email.');
    	}
    	if(get_magic_quotes_gpc()) {
    		$forgotpassword = htmlspecialchars(stripslashes($_POST['forgotpassword']));
    	} 
    	else {
    		$forgotpassword = htmlspecialchars($_POST['forgotpassword']);
    	}
    	//Make sure it's a valid email address, last thing we want is some sort of exploit!
    	if (!check_email_address($_POST['forgotpassword'])) {
      		error('Email Not Valid - Must be in format of name@domain.tld');
    	}
        // Lets see if the email exists
        $sql = "SELECT COUNT(*) FROM configuration WHERE configuration_key = 'STORE_OWNER_EMAIL_ADDRESS'";
        $result = mysql_query($sql)or die('Could not find member: ' . mysql_error());
        if (!mysql_result($result,0,0)>0) {
            error('Email Not Found!');
        }
    
    	//Generate a RANDOM MD5 Hash for a password
    	$random_password=md5(uniqid(rand()));
    	
    	//Take the first 8 digits and use them as the password we intend to email the user
    	$emailpassword=substr($random_password, 0, 8);
    	
    	//Encrypt $emailpassword in MD5 format for the database
    	$newpassword = md5($emailpassword);

    That's the part that is making me cofused:
    Code:
    
            // Make a safe query
           	$query = sprintf("select ID from administrator where sPassword='$newpassword' and sGUID<>'logged off'",
                        mysql_real_escape_string($newpassword));
    					
    					mysql_query($query)or die('Could not update members: ' . mysql_error());


    Code:
    
    
    
    //Email out the infromation
    $subject = "Your New Password"; 
    $message = "Your new password is as follows:
    ---------------------------- 
    Password: $emailpassword
    ---------------------------- 
    Please make note this information has been encrypted into our database 
    
    This email was automatically generated."; 
                           
              if(!mail($forgotpassword, $subject, $message,  "FROM: $site_name <$site_email>")){ 
                 die ("Sending Email Failed, Please Contact Site Admin! ($site_email)"); 
              }else{ 
                    error('New Password Sent!.');
             } 
    		
    	}
    	
    else {
    ?>
          <form name="forgotpasswordform" action="" method="post">
            <table border="0" cellspacing="0" cellpadding="3" width="100%">
              <caption>
              <div>Forgot Password</div>
              </caption>
              <tr>
                <td>Email Address:</td>
                <td><input name="forgotpassword" type="text" value="" id="forgotpassword" /></td>
              </tr>
              <tr>
                <td colspan="2" class="footer"><input type="submit" name="submit" value="Submit" class="mainoption" /></td>
              </tr>
            </table>
          </form>
          <?
    }
    ?>
    Attached Files
    Last edited by matheussousuke; Oct 6 '10, 05:52 PM. Reason: keywords
  • dlite922
    Recognized Expert Top Contributor
    • Dec 2007
    • 1586

    #2
    Why is that part making you confused? sprintf formats a string. It goes into a variable. The variable is given to mysql_query().

    But don't know why you're not grabbing the result of mysql_query(). What's the point of running the query?


    Dan

    Comment

    • matheussousuke
      New Member
      • Sep 2009
      • 249

      #3
      because I'm getting a MD5 instead of a hash mysql PASSWORD.

      Comment

      • matheussousuke
        New Member
        • Sep 2009
        • 249

        #4
        I'm trying to retrieve the e-mail through a form, using this sql command

        Code:
          $sql = "SELECT 'configuration_id='3' FROM administrator WHERE configuration_value = '$forgotpassword'";
        The logic is correct, it selects the email from id 3, and it has to work if you type the correct email on the form, but I'm getting this error:

        Code:
        You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '3' FROM administrator WHERE configuration_value = 'matheuswebdesigner@hotmail.co' at line 1
        here, an image of the database

        the part that is croped is "configuration_ value", where has the email on configuration_i d "3".

        Comment

        • matheussousuke
          New Member
          • Sep 2009
          • 249

          #5
          Is there anybody there?

          That's the last thing, please help me here, I have to present that work tomorrow.

          thx

          Comment

          • Niheel
            Recognized Expert Moderator Top Contributor
            • Jul 2005
            • 2433

            #6
            There's an extra ' after the select in your SQL query.
            niheel @ bytes

            Comment

            • matheussousuke
              New Member
              • Sep 2009
              • 249

              #7
              Thx for the help, I solved it.

              If you are desperate, LIKE I was in the last 7 days!!!!!!!!!!! !!! about a forgot password script, this one is fulling working, just adjust it to use with your database, it sends a new password to the email of the administrator. WORKS LIKE A CHARM, and it's very simple to configure (NOW IT IS...) so, use it at will.

              As they say in Brazil, "Divirta-se sem moderação (eles dizem isso? rsrsrsrs)".


              There you go



              FIRST OF ALL, BYTES MODERATORS, please leave it outside the "code" tags, because it gets easiest to copy, if you put it on the "code" tag, you get this "#" after u copy and paste.




              Code:
              <?
              //Connect to the MySQL Database
              include 'includes/application_top.php';
              
               //this function will display error messages in alert boxes, used for login forms so if a field is invalid it will still keep the info
               //use error('foobar');
               function error($msg) {
                  ?>
                   <html>
                 <head>
                   <script language="JavaScript">
                   <!--
                       alert("<?=$msg?>");
                       history.back();
                   //-->
                  </script>
                  </head>
                 <body>
                   </body>
                   </html>
                   <?
                   exit;
               }
                
               //This functions checks and makes sure the email address that is being added to database is valid in format. 
               function check_email_address($email) {
                 // First, we check that there's one @ symbol, and that the lengths are right
                 if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
                   // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
                   return false;
                 }
                 // Split it into sections to make life easier
                 $email_array = explode("@", $email);
                 $local_array = explode(".", $email_array[0]);
                 for ($i = 0; $i < sizeof($local_array); $i++) {
                    if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
                     return false;
                   }
                 }  
                
                
              
                
                
                 if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
                   $domain_array = explode(".", $email_array[1]);
                   if (sizeof($domain_array) < 2) {
                       return false; // Not enough parts to domain
                   }
                   for ($i = 0; $i < sizeof($domain_array); $i++) {
                     if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
                       return false;
                     }
                   }
                 }
                 return true;
               }
                
                
               if (isset($_POST['submit'])) {
                
                   if ($_POST['forgotpassword']=='') {
                       error('Por favor, preencha o campo de email.');
                   }
                   if(get_magic_quotes_gpc()) {
                       $forgotpassword = htmlspecialchars(stripslashes($_POST['forgotpassword']));
                   } 
                   else {
                       $forgotpassword = htmlspecialchars($_POST['forgotpassword']);
                   }
                   //Make sure it's a valid email address, last thing we want is some sort of exploit!
                   if (!check_email_address($_POST['forgotpassword'])) {
                         error('Email digitado de forma incorreta.');
                   }
                   // Lets see if the email exists
              	 
                
              	 /*ORIGINAL
              	 
              	   // Lets see if the email exists
                  $sql = "SELECT COUNT(*) FROM members WHERE user_email = '$forgotpassword'";
                  $result = mysql_query($sql)or die('Could not find member: ' . mysql_error());
                  if (!mysql_result($result,0,0)&gt;0) {
                      error('Email Not Found!');
                  }	 
              	 
              	 */
              	 
              		 
              	  $soea='STORE_OWNER_EMAIL_ADDRESS';
              	  $sql = "SELECT COUNT(*) FROM configuration WHERE configuration_value='$forgotpassword'";
                   $result = mysql_query($sql)or die('Erro, esse email não existe no banco de dados, você se esqueceu de inserir seu email em "Email do proprietário", dentro de "Configuração --> Minha Loja" ?  ' . mysql_error());
                   if (!mysql_result($result,0,0)>0) {
                       error('Email não encontrado!');
                   }
                
                   //Generate a RANDOM Hash for a password
                   $random_password= (uniqid(rand()));
                
                   //Take the first 8 digits and use them as the password we intend to email the user
                   $emailpassword=substr($random_password, 0, 8);
                
                   //Encrypt $emailpassword for the database
                   $newpassword = ($emailpassword);
                // Make a safe query update administrator set sPassword = '$newpassword
                        	  
              		  
              		  
              		  
              		    $query = sprintf("UPDATE administrator SET sPassword=PASSWORD('$newpassword')",
                                   mysql_real_escape_string($newpassword));
                
                                   mysql_query($query)or die('Não pôde atualizar tabela: ' . mysql_error());
              
              					 
              					 
              					 
              					 
              					 
               //Email out the infromation
               $subject = "Nova senha administrativa de sua loja virtual"; 
               $message = "A seguir está a sua nova senha:
               ---------------------------- 
               Password: $emailpassword
               ---------------------------- 
               Após acessar seu site, você poderá trocar de senha a qualquer momento, clicando em 'Minha Conta' . 
               Este email foi gerado automaticamente."; 
                
                         if(!mail($forgotpassword, $subject, $message,  "FROM: $site_name <$site_email>")){ 
                            die ("Falha ao enviar email, por favor, tente novamente"); 
                         }else{ 
                               error('Nova senha enviada!.');
                        } 
                
                   }
                
               else {
               ?>
                     <form name="forgotpasswordform" action="" method="post">
                       <table border="0" cellspacing="0" cellpadding="3" width="100%">
                         
                         <td><caption>Esqueceu sua senha?<br>Insira o endereço de email que<br>você salvou como "Email do Proprietário", na<br> configuração de sua loja, que sua nova senha será enviada:
              		    
              		   
              		   </caption></td>
                         
                        
                           
                           <td align="center"><input name="forgotpassword" type="text" value="" id="forgotpassword" /></td>
                       
                         <tr>
                           <td align="center" colspan="2" class="footer"><input type="submit" name="submit" value="Enviar" class="mainoption" /></td>
                         </tr>
                       </table>
                     </form>
                     <?
               }
              ?>
              Last edited by Niheel; Oct 9 '10, 01:27 AM.

              Comment

              • matheussousuke
                New Member
                • Sep 2009
                • 249

                #8
                Please, set this post as SOLVED SUCCESSFULLY

                ONce again, thx for the support, I really like this forum.

                Comment

                • Dormilich
                  Recognized Expert Expert
                  • Aug 2008
                  • 8694

                  #9
                  FIRST OF ALL, BYTES MODERATORS, please leave it outside the "code" tags, because it gets easiest to copy, if you put it on the "code" tag, you get this "#" after u copy and paste.
                  click "Line Numbers" then "Select".

                  Comment

                  • matheussousuke
                    New Member
                    • Sep 2009
                    • 249

                    #10
                    Ok, thank you ;)

                    Comment

                    Working...