Geetha
Geetha

Reputation: 353

Generate Random password and send to email in PHP

when you register on my site your password is stored using $hashedPass = md5($password);.

the below code is my forgot password code :

Problem is : its redirect to denied page.

Friends may i know where i made a mistake in the below code Please Help me Friends

<?php
session_start();  // Start Session
//Connect to the database through our include 
    include_once "connect_to_mysql.php";
session_register("session");
// This is displayed if all the fields are not filled in
$empty_fields_message = "<p>Please go back and complete all the fields in the form.</p>Click <a class=\"two\" href=\"javascript:history.go(-1)\">here</a> to go back";
// Convert to simple variables  
$email = $_POST['email'];
if (!isset($_POST['email'])) {

?>
       <?php
}
elseif (empty($email)) {
    echo $empty_fields_message;
}
else {
$email=mysql_real_escape_string($email);
$status = "OK";
$msg="";
//error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
$msg="Your email address is not correct<BR>"; 
$status= "NOTOK";}

echo "<br><br>";
if($status=="OK"){  $query="SELECT email,username FROM members WHERE email = '$email'";
$st=mysql_query($query);
$recs=mysql_num_rows($st);
$row=mysql_fetch_object($st);
$em=$row->email;// email is stored to a variable
 if ($recs == 0) {
//Redirect to denied page.
 print "<script language='Javascript'>document.location.replace('forgotenpass_denied.php');</script>";
}
function makeRandomPassword() { 
          $salt = "abchefghjkmnpqrstuvwxyz0123456789"; 
          srand((double)microtime()*1000000);  
          $i = 0; 
          while ($i <= 7) { 
                $num = rand() % 33; 
                $tmp = substr($salt, $num, 1); 
                $pass = $pass . $tmp; 
                $i++; 
          } 
          return $pass; 
    } 
    $random_password = makeRandomPassword();  
    $password = md5($random_password); 

    $sql = mysql_query("UPDATE members SET password='$password'  WHERE email='$email'"); 

     $to = "$email";
    // Change this to your site admin email
    $from = "[email protected]";
    $subject = "Your Password Has been reset"; 
    $message = "Hi, we have reset your password. 

    Your New Password is: $random_password 

    http://www.trytek.tryteksolutions.co.in/login.php
    Once logged in you can change your password 

    Thanks! 
    Admin 

    This is an automated response, DO NOT REPLY!"; 

   $headers = "From: $from\r\n";
        $headers .= "Content-type: text/html\r\n";
        $to = "$to";
        // Finally send the activation email to the member
        mail($to, $subject, $message, $headers);
    print "<script language='Javascript'>document.location.replace('forgotenpass_sucess.php');</script>"; 
 } 
 else {echo "<center><font face='Verdana' size='2' color=red >$msg <br><br><input type='button' value='Retry' onClick='history.go(-1)'></center></font>";}
}
?>

Upvotes: 0

Views: 3492

Answers (3)

eggyal
eggyal

Reputation: 125925

There is so much wrong here, that I barely know where to start.

  1. As documented under mysql_num_rows():

    Return Values 

    The number of rows in a result set on success or FALSE on failure.

    As documented under PHP type comparison tables, FALSE == 0 is true. Therefore, the boolean expression $recs == 0 will evaluate to TRUE even if mysql_num_rows() failed. You must instead use a strict comparison $recs === 0 to ensure that it only evaluates to TRUE if its value is a zero.

    You should also check whether function calls failed and, if they did, perform suitable error handling. For example:

    mysql_query($query) or die(mysql_error());
    
  2. That said, as documented under mysql_query():

    Warning

    This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  3. As documented under Strings:

    Double quoted

    If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

    ╔════════════════════╦═══════════════════════════════════════════════════════════════════════════════════════════════════╗
    ║      Sequence      ║                                              Meaning                                              ║
    ╠════════════════════╬═══════════════════════════════════════════════════════════════════════════════════════════════════╣
    ║ \n                 ║ linefeed (LF or 0x0A (10) in ASCII)                                                               ║
    ║ \r                 ║ carriage return (CR or 0x0D (13) in ASCII)                                                        ║
    ║ \t                 ║ horizontal tab (HT or 0x09 (9) in ASCII)                                                          ║
    ║ \v                 ║ vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)                                         ║
    ║ \e                 ║ escape (ESC or 0x1B (27) in ASCII) (since PHP 5.4.0)                                              ║
    ║ \f                 ║ form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)                                            ║
    ║ \\                 ║ backslash                                                                                         ║
    ║ \$                 ║ dollar sign                                                                                       ║
    ║ \"                 ║ double-quote                                                                                      ║
    ║ \[0-7]{1,3}        ║ the sequence of characters matching the regular expression is a character in octal notation       ║
    ║ \x[0-9A-Fa-f]{1,2} ║ the sequence of characters matching the regular expression is a character in hexadecimal notation ║
    ╚════════════════════╩═══════════════════════════════════════════════════════════════════════════════════════════════════╝
    

    As in single quoted strings, escaping any other character will result in the backslash being printed too.

    Your string "/([\w\-]+\@[\w\-]+\.[\w\-]+)/" therefore relies on the fact that \w, \-, \@ and \. are not valid double-quoted string escape sequences. You should at very least escape the backslashes in order to explicitly include them in the regular expression:

    if (!preg_match("/([\\w\\-]+\\@[\\w\\-]+\\.[\\w\\-]+)/",$email)) {
    

    That said, since @ is not a PCRE meta-character it actually does not need to be escaped.

    Furthermore, the character class [\w\-] encompasses letters, digits, underscores and hyphens: which is not sufficient to match an email address—look at some examples of valid email addresses to see why; indeed, regular expressions cannot be used to validate email addresses (one should use a parser instead).

    However, in your case, I don't see why it is necessary to validate the email address at all—just go straight into looking it up in your database.

  4. As documented under md5():

     Note: Secure password hashing

    It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm. See here for details.

  5. Others have already observed that you can (and probably should) redirect using HTTP headers rather than JavaScript.

  6. There are a bunch of other oddities:

    $row=mysql_fetch_object($st);
    $em=$row->email;// email is stored to a variable
    

    It is not clear why you do this: after all, you already have the value of $em in $email. Also, bear in mind that your query may have returned more than one record, whereas this will only fetch the first one thereof.

    $to = "$email";
    

    Why not just $to = $email (or indeed, just use $email directly as the mail() function call's first argument)? You're requiring the PHP to undertake unnecessary parsing in order to perform a simple assignment. For that matter, you are using double-quoted string literals throughout your code where single-quoted literals (that have less parsing overhead and protect you from accidentally including unescaped variables) would suffice.

    $to = "$to";
    

    I have no idea what could be the purpose of this line of code.

    $status = "OK";
    $status= "NOTOK";
    if($status=="OK")
    

    Why not use a boolean instead of string comparison?

  7. In this day & age, one really ought to be using CSS instead of <center>, <font> etc.

Upvotes: 2

Steven Liekens
Steven Liekens

Reputation: 14113

The problem is obviously somewhere in this block:

$query="SELECT email,username FROM members WHERE email = '$email'";
$st=mysql_query($query);
$recs=mysql_num_rows($st);
$row=mysql_fetch_object($st);
$em=$row->email;// email is stored to a variable
 if ($recs == 0) {
//Redirect to denied page.
 print "<script language='Javascript'>document.location.replace('forgotenpass_denied.php');</script>";
}

More specifically, the problem is that your query is returning 0 records (or FALSE on error). Unfortunately, my crystal ball is out of order, so I can't tell you why. Nevertheless, here are some things to verify:

  • Do you have a working database connection?
  • Do the table/field names in the query match the database schema?
  • Does $email actually exists in table members?

Upvotes: 0

Cesar Bielich
Cesar Bielich

Reputation: 4945

Maybe try using the full server path for

print "<script language='Javascript'>document.location.replace('forgotenpass_denied.php');</script>";

and

print "<script language='Javascript'>document.location.replace('forgotenpass_sucess.php');</script>";

Instead of using

document.location.replace('forgotenpass_denied.php')

Try

document.location.replace('/home/xxxxx/www/forgotenpass_denied.php')

Upvotes: 0

Related Questions