By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,024 Members | 1,945 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,024 IT Pros & Developers. It's quick & easy.

Forgot password script

matheussousuke
100+
P: 249
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.

Expand|Select|Wrap|Line Numbers
  1.  
  2. <?
  3. define('IN_SCRIPT', true);
  4. // Start a session
  5. session_start();
  6.  
  7. //Connect to the MySQL Database
  8. include 'includes/application_top.php';
  9.  
  10. //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
  11. //use error('foobar');
  12. function error($msg) {
  13.     ?>
  14.     <html>
  15.     <head>
  16.     <script language="JavaScript">
  17.     <!--
  18.         alert("<?=$msg?>");
  19.         history.back();
  20.     //-->
  21.     </script>
  22.     </head>
  23.     <body>
  24.     </body>
  25.     </html>
  26.     <?
  27.     exit;
  28. }
  29.  
  30. //This functions checks and makes sure the email address that is being added to database is valid in format. 
  31. function check_email_address($email) {
  32.   // First, we check that there's one @ symbol, and that the lengths are right
  33.   if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
  34.     // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
  35.     return false;
  36.   }
  37.   // Split it into sections to make life easier
  38.   $email_array = explode("@", $email);
  39.   $local_array = explode(".", $email_array[0]);
  40.   for ($i = 0; $i < sizeof($local_array); $i++) {
  41.      if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
  42.       return false;
  43.     }
  44.   }  
  45.  
  46.  
  47.   $soea='STORE_OWNER_EMAIL_ADDRESS';
  48.  
  49.  
  50.   if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
  51.     $domain_array = explode(".", $email_array[1]);
  52.     if (sizeof($domain_array) < 2) {
  53.         return false; // Not enough parts to domain
  54.     }
  55.     for ($i = 0; $i < sizeof($domain_array); $i++) {
  56.       if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
  57.         return false;
  58.       }
  59.     }
  60.   }
  61.   return true;
  62. }
  63.  
  64.  
  65. if (isset($_POST['submit'])) {
  66.  
  67.     if ($_POST['forgotpassword']=='') {
  68.         error('Please Fill in Email.');
  69.     }
  70.     if(get_magic_quotes_gpc()) {
  71.         $forgotpassword = htmlspecialchars(stripslashes($_POST['forgotpassword']));
  72.     } 
  73.     else {
  74.         $forgotpassword = htmlspecialchars($_POST['forgotpassword']);
  75.     }
  76.     //Make sure it's a valid email address, last thing we want is some sort of exploit!
  77.     if (!check_email_address($_POST['forgotpassword'])) {
  78.           error('Email Not Valid - Must be in format of name@domain.tld');
  79.     }
  80.     // Lets see if the email exists
  81.     $sql = "SELECT COUNT(*) FROM configuration WHERE configuration_key = 'STORE_OWNER_EMAIL_ADDRESS'";
  82.     $result = mysql_query($sql)or die('Could not find member: ' . mysql_error());
  83.     if (!mysql_result($result,0,0)>0) {
  84.         error('Email Not Found!');
  85.     }
  86.  
  87.     //Generate a RANDOM MD5 Hash for a password
  88.     $random_password=md5(uniqid(rand()));
  89.  
  90.     //Take the first 8 digits and use them as the password we intend to email the user
  91.     $emailpassword=substr($random_password, 0, 8);
  92.  
  93.     //Encrypt $emailpassword in MD5 format for the database
  94.     $newpassword = md5($emailpassword);
  95.  
  96.  
  97.  

That's the part that is making me cofused:
Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3.         // Make a safe query
  4.            $query = sprintf("select ID from administrator where sPassword='$newpassword' and sGUID<>'logged off'",
  5.                     mysql_real_escape_string($newpassword));
  6.  
  7.                     mysql_query($query)or die('Could not update members: ' . mysql_error());
  8.  
  9.  


Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3.  
  4.  
  5. //Email out the infromation
  6. $subject = "Your New Password"; 
  7. $message = "Your new password is as follows:
  8. ---------------------------- 
  9. Password: $emailpassword
  10. ---------------------------- 
  11. Please make note this information has been encrypted into our database 
  12.  
  13. This email was automatically generated."; 
  14.  
  15.           if(!mail($forgotpassword, $subject, $message,  "FROM: $site_name <$site_email>")){ 
  16.              die ("Sending Email Failed, Please Contact Site Admin! ($site_email)"); 
  17.           }else{ 
  18.                 error('New Password Sent!.');
  19.          } 
  20.  
  21.     }
  22.  
  23. else {
  24. ?>
  25.       <form name="forgotpasswordform" action="" method="post">
  26.         <table border="0" cellspacing="0" cellpadding="3" width="100%">
  27.           <caption>
  28.           <div>Forgot Password</div>
  29.           </caption>
  30.           <tr>
  31.             <td>Email Address:</td>
  32.             <td><input name="forgotpassword" type="text" value="" id="forgotpassword" /></td>
  33.           </tr>
  34.           <tr>
  35.             <td colspan="2" class="footer"><input type="submit" name="submit" value="Submit" class="mainoption" /></td>
  36.           </tr>
  37.         </table>
  38.       </form>
  39.       <?
  40. }
  41. ?>
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
Attached Images
File Type: jpg dbclothes1.jpg (44.3 KB, 159 views)
File Type: jpg dbclothes2.jpg (32.2 KB, 413 views)
Oct 6 '10 #1

✓ answered by matheussousuke

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.




Expand|Select|Wrap|Line Numbers
  1. <?
  2. //Connect to the MySQL Database
  3. include 'includes/application_top.php';
  4.  
  5.  //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
  6.  //use error('foobar');
  7.  function error($msg) {
  8.     ?>
  9.      <html>
  10.    <head>
  11.      <script language="JavaScript">
  12.      <!--
  13.          alert("<?=$msg?>");
  14.          history.back();
  15.      //-->
  16.     </script>
  17.     </head>
  18.    <body>
  19.      </body>
  20.      </html>
  21.      <?
  22.      exit;
  23.  }
  24.  
  25.  //This functions checks and makes sure the email address that is being added to database is valid in format. 
  26.  function check_email_address($email) {
  27.    // First, we check that there's one @ symbol, and that the lengths are right
  28.    if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
  29.      // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
  30.      return false;
  31.    }
  32.    // Split it into sections to make life easier
  33.    $email_array = explode("@", $email);
  34.    $local_array = explode(".", $email_array[0]);
  35.    for ($i = 0; $i < sizeof($local_array); $i++) {
  36.       if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
  37.        return false;
  38.      }
  39.    }  
  40.  
  41.  
  42.  
  43.  
  44.  
  45.    if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
  46.      $domain_array = explode(".", $email_array[1]);
  47.      if (sizeof($domain_array) < 2) {
  48.          return false; // Not enough parts to domain
  49.      }
  50.      for ($i = 0; $i < sizeof($domain_array); $i++) {
  51.        if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
  52.          return false;
  53.        }
  54.      }
  55.    }
  56.    return true;
  57.  }
  58.  
  59.  
  60.  if (isset($_POST['submit'])) {
  61.  
  62.      if ($_POST['forgotpassword']=='') {
  63.          error('Por favor, preencha o campo de email.');
  64.      }
  65.      if(get_magic_quotes_gpc()) {
  66.          $forgotpassword = htmlspecialchars(stripslashes($_POST['forgotpassword']));
  67.      } 
  68.      else {
  69.          $forgotpassword = htmlspecialchars($_POST['forgotpassword']);
  70.      }
  71.      //Make sure it's a valid email address, last thing we want is some sort of exploit!
  72.      if (!check_email_address($_POST['forgotpassword'])) {
  73.            error('Email digitado de forma incorreta.');
  74.      }
  75.      // Lets see if the email exists
  76.  
  77.  
  78.      /*ORIGINAL
  79.  
  80.        // Lets see if the email exists
  81.     $sql = "SELECT COUNT(*) FROM members WHERE user_email = '$forgotpassword'";
  82.     $result = mysql_query($sql)or die('Could not find member: ' . mysql_error());
  83.     if (!mysql_result($result,0,0)&gt;0) {
  84.         error('Email Not Found!');
  85.     }     
  86.  
  87.      */
  88.  
  89.  
  90.       $soea='STORE_OWNER_EMAIL_ADDRESS';
  91.       $sql = "SELECT COUNT(*) FROM configuration WHERE configuration_value='$forgotpassword'";
  92.      $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());
  93.      if (!mysql_result($result,0,0)>0) {
  94.          error('Email não encontrado!');
  95.      }
  96.  
  97.      //Generate a RANDOM Hash for a password
  98.      $random_password= (uniqid(rand()));
  99.  
  100.      //Take the first 8 digits and use them as the password we intend to email the user
  101.      $emailpassword=substr($random_password, 0, 8);
  102.  
  103.      //Encrypt $emailpassword for the database
  104.      $newpassword = ($emailpassword);
  105.   // Make a safe query update administrator set sPassword = '$newpassword
  106.  
  107.  
  108.  
  109.  
  110.             $query = sprintf("UPDATE administrator SET sPassword=PASSWORD('$newpassword')",
  111.                      mysql_real_escape_string($newpassword));
  112.  
  113.                      mysql_query($query)or die('Não pôde atualizar tabela: ' . mysql_error());
  114.  
  115.  
  116.  
  117.  
  118.  
  119.  
  120.  //Email out the infromation
  121.  $subject = "Nova senha administrativa de sua loja virtual"; 
  122.  $message = "A seguir está a sua nova senha:
  123.  ---------------------------- 
  124.  Password: $emailpassword
  125.  ---------------------------- 
  126.  Após acessar seu site, você poderá trocar de senha a qualquer momento, clicando em 'Minha Conta' . 
  127.  Este email foi gerado automaticamente."; 
  128.  
  129.            if(!mail($forgotpassword, $subject, $message,  "FROM: $site_name <$site_email>")){ 
  130.               die ("Falha ao enviar email, por favor, tente novamente"); 
  131.            }else{ 
  132.                  error('Nova senha enviada!.');
  133.           } 
  134.  
  135.      }
  136.  
  137.  else {
  138.  ?>
  139.        <form name="forgotpasswordform" action="" method="post">
  140.          <table border="0" cellspacing="0" cellpadding="3" width="100%">
  141.  
  142.            <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:
  143.  
  144.  
  145.            </caption></td>
  146.  
  147.  
  148.  
  149.              <td align="center"><input name="forgotpassword" type="text" value="" id="forgotpassword" /></td>
  150.  
  151.            <tr>
  152.              <td align="center" colspan="2" class="footer"><input type="submit" name="submit" value="Enviar" class="mainoption" /></td>
  153.            </tr>
  154.          </table>
  155.        </form>
  156.        <?
  157.  }
  158. ?>

Share this Question
Share on Google+
9 Replies


dlite922
Expert 100+
P: 1,584
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
Oct 7 '10 #2

matheussousuke
100+
P: 249
because I'm getting a MD5 instead of a hash mysql PASSWORD.
Oct 7 '10 #3

matheussousuke
100+
P: 249
I'm trying to retrieve the e-mail through a form, using this sql command

Expand|Select|Wrap|Line Numbers
  1.   $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:

Expand|Select|Wrap|Line Numbers
  1. 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_id "3".
Oct 8 '10 #4

matheussousuke
100+
P: 249
Is there anybody there?

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

thx
Oct 8 '10 #5

Expert Mod 100+
P: 2,327
There's an extra ' after the select in your SQL query.
Oct 9 '10 #6

matheussousuke
100+
P: 249
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.




Expand|Select|Wrap|Line Numbers
  1. <?
  2. //Connect to the MySQL Database
  3. include 'includes/application_top.php';
  4.  
  5.  //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
  6.  //use error('foobar');
  7.  function error($msg) {
  8.     ?>
  9.      <html>
  10.    <head>
  11.      <script language="JavaScript">
  12.      <!--
  13.          alert("<?=$msg?>");
  14.          history.back();
  15.      //-->
  16.     </script>
  17.     </head>
  18.    <body>
  19.      </body>
  20.      </html>
  21.      <?
  22.      exit;
  23.  }
  24.  
  25.  //This functions checks and makes sure the email address that is being added to database is valid in format. 
  26.  function check_email_address($email) {
  27.    // First, we check that there's one @ symbol, and that the lengths are right
  28.    if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
  29.      // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
  30.      return false;
  31.    }
  32.    // Split it into sections to make life easier
  33.    $email_array = explode("@", $email);
  34.    $local_array = explode(".", $email_array[0]);
  35.    for ($i = 0; $i < sizeof($local_array); $i++) {
  36.       if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
  37.        return false;
  38.      }
  39.    }  
  40.  
  41.  
  42.  
  43.  
  44.  
  45.    if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
  46.      $domain_array = explode(".", $email_array[1]);
  47.      if (sizeof($domain_array) < 2) {
  48.          return false; // Not enough parts to domain
  49.      }
  50.      for ($i = 0; $i < sizeof($domain_array); $i++) {
  51.        if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
  52.          return false;
  53.        }
  54.      }
  55.    }
  56.    return true;
  57.  }
  58.  
  59.  
  60.  if (isset($_POST['submit'])) {
  61.  
  62.      if ($_POST['forgotpassword']=='') {
  63.          error('Por favor, preencha o campo de email.');
  64.      }
  65.      if(get_magic_quotes_gpc()) {
  66.          $forgotpassword = htmlspecialchars(stripslashes($_POST['forgotpassword']));
  67.      } 
  68.      else {
  69.          $forgotpassword = htmlspecialchars($_POST['forgotpassword']);
  70.      }
  71.      //Make sure it's a valid email address, last thing we want is some sort of exploit!
  72.      if (!check_email_address($_POST['forgotpassword'])) {
  73.            error('Email digitado de forma incorreta.');
  74.      }
  75.      // Lets see if the email exists
  76.  
  77.  
  78.      /*ORIGINAL
  79.  
  80.        // Lets see if the email exists
  81.     $sql = "SELECT COUNT(*) FROM members WHERE user_email = '$forgotpassword'";
  82.     $result = mysql_query($sql)or die('Could not find member: ' . mysql_error());
  83.     if (!mysql_result($result,0,0)&gt;0) {
  84.         error('Email Not Found!');
  85.     }     
  86.  
  87.      */
  88.  
  89.  
  90.       $soea='STORE_OWNER_EMAIL_ADDRESS';
  91.       $sql = "SELECT COUNT(*) FROM configuration WHERE configuration_value='$forgotpassword'";
  92.      $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());
  93.      if (!mysql_result($result,0,0)>0) {
  94.          error('Email não encontrado!');
  95.      }
  96.  
  97.      //Generate a RANDOM Hash for a password
  98.      $random_password= (uniqid(rand()));
  99.  
  100.      //Take the first 8 digits and use them as the password we intend to email the user
  101.      $emailpassword=substr($random_password, 0, 8);
  102.  
  103.      //Encrypt $emailpassword for the database
  104.      $newpassword = ($emailpassword);
  105.   // Make a safe query update administrator set sPassword = '$newpassword
  106.  
  107.  
  108.  
  109.  
  110.             $query = sprintf("UPDATE administrator SET sPassword=PASSWORD('$newpassword')",
  111.                      mysql_real_escape_string($newpassword));
  112.  
  113.                      mysql_query($query)or die('Não pôde atualizar tabela: ' . mysql_error());
  114.  
  115.  
  116.  
  117.  
  118.  
  119.  
  120.  //Email out the infromation
  121.  $subject = "Nova senha administrativa de sua loja virtual"; 
  122.  $message = "A seguir está a sua nova senha:
  123.  ---------------------------- 
  124.  Password: $emailpassword
  125.  ---------------------------- 
  126.  Após acessar seu site, você poderá trocar de senha a qualquer momento, clicando em 'Minha Conta' . 
  127.  Este email foi gerado automaticamente."; 
  128.  
  129.            if(!mail($forgotpassword, $subject, $message,  "FROM: $site_name <$site_email>")){ 
  130.               die ("Falha ao enviar email, por favor, tente novamente"); 
  131.            }else{ 
  132.                  error('Nova senha enviada!.');
  133.           } 
  134.  
  135.      }
  136.  
  137.  else {
  138.  ?>
  139.        <form name="forgotpasswordform" action="" method="post">
  140.          <table border="0" cellspacing="0" cellpadding="3" width="100%">
  141.  
  142.            <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:
  143.  
  144.  
  145.            </caption></td>
  146.  
  147.  
  148.  
  149.              <td align="center"><input name="forgotpassword" type="text" value="" id="forgotpassword" /></td>
  150.  
  151.            <tr>
  152.              <td align="center" colspan="2" class="footer"><input type="submit" name="submit" value="Enviar" class="mainoption" /></td>
  153.            </tr>
  154.          </table>
  155.        </form>
  156.        <?
  157.  }
  158. ?>
Oct 9 '10 #7

matheussousuke
100+
P: 249
Please, set this post as SOLVED SUCCESSFULLY

ONce again, thx for the support, I really like this forum.
Oct 9 '10 #8

Dormilich
Expert Mod 5K+
P: 8,639
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".
Oct 9 '10 #9

matheussousuke
100+
P: 249
Ok, thank you ;)
Oct 9 '10 #10

Post your reply

Sign in to post your reply or Sign up for a free account.