php - 生成随 secret 码并用 PHP 发送到电子邮件

标签 php mysql

当您在我的网站上注册时,您的密码将使用 $hashedPass = md5($password); 存储。

下面的代码是我忘记密码的代码:

问题是:它重定向到被拒绝的页面。

friend 们我可以知道我在下面的代码中哪里犯了错误吗? 请 friend 们帮助我

<?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 = "geetha.victor@tryteksolutions.com";
    $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>";}
}
?>

最佳答案

这里有太多错误,我几乎不知道从哪里开始。

  1. mysql_num_rows() 下所述:

    Return Values 

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

    PHP type comparison tables 下所述, FALSE == 0是真的。因此, bool 表达式 $recs == 0将评估为 TRUE即使mysql_num_rows()失败的。您必须改为使用严格比较 $recs === 0确保它的计算结果仅为 TRUE如果其值为零。

    您还应该检查函数调用是否失败,如果失败,则执行适当的错误处理。例如:

    mysql_query($query) or die(mysql_error());
    
  2. 也就是说,如 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. 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.

    您的字符串"/([\w\-]+\@[\w\-]+\.[\w\-]+)/"因此依赖于这样一个事实: \w , \- , \@\.不是有效的双引号字符串转义序列。您至少应该转义反斜杠,以便将它们显式包含在正则表达式中:

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

    也就是说,从 @ 开始不是PCRE meta-character它实际上不需要转义。

    此外,字符类 [\w\-]包含字母、数字、下划线和连字符:这不足以匹配电子邮件地址 - 请参阅 some examples of valid email addresses看看为什么;事实上,正则表达式cannot be used验证电子邮件地址(应该使用解析器)。

    但是,就您的情况而言,我根本不明白为什么有必要验证电子邮件地址 - 只需直接在数据库中查找即可。

  4. 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. 其他人已经观察到您可以(并且可能应该)使用 HTTP header 而不是 JavaScript 进行重定向。

  6. 还有很多其他奇怪的地方:

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

    尚不清楚为什么要这样做:毕竟,您已经拥有 $em 的值。在$email 。另外,请记住,您的查询可能返回多个记录,而这只会获取其中的第一个记录。

    $to = "$email";
    

    为什么不只是 $to = $email (或者实际上,直接使用 $email 作为 mail() 函数调用的第一个参数)?您需要 PHP 进行不必要的解析才能执行简单的分配。就此而言,您在整个代码中使用双引号字符串文字,其中单引号文字(解析开销较小并防止您意外包含未转义的变量)就足够了。

    $to = "$to";
    

    我不知道这行代码的目的是什么。

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

    为什么不使用 bool 值而不是字符串比较?

  7. 在当今时代,一个人确实应该使用 CSS 而不是 <center> , <font>等等

关于php - 生成随 secret 码并用 PHP 发送到电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21671563/

相关文章:

mysql - libmemcached 路径?

mysql - 有限制的分组是如何工作的

php - 使用正则表达式查找字符串中的单词数组

php - 在JQuery中创建动态html表后,应用另一个JQuery(表排序器)

javascript - AJAX:使用数组值的背景颜色更改功能不起作用?

mysql - 改进 SQL 查询,以便按 "external"表中存储的值过滤结果

java - 显示 : exception is never thrown in body of try statement 的语法警告

MySQL 在 where 子句中分配用户定义的变量

php - PHP 中的 XDebug 分析 - 无法获取输出

php - 在 PHP 中将变量名转换为数组