【问题标题】:Change password on user request PHP根据用户请求更改密码 PHP
【发布时间】:2018-04-20 14:13:22
【问题描述】:

我正在尝试制作一个 php 脚本来检查电子邮件是否在数据库中,然后随机生成密码,在数据库中更改密码并发送电子邮件通知用户。该代码正确检查输入的电子邮件是否有效,但不会更改密码。粘贴代码并提前感谢您。我是初学者,所以请尽量避免批评代码不好,我是来学习的。

require_once("database/DatabaseConnection.php");

unset($_SESSION['success_message']);
unset($_SESSION['error_message']);


function died($error)
{
    // your error code can go here
    echo "We are very sorry, but you have to input correct email. ";
    echo "If there was anything else you will see errors below.<br /><br />";
    echo $error . "<br /><br />";
    echo "Please go back and fix these errors.<br /><br />";
    die();
}

// validation expected data exists
if (!isset($_POST['logMail'])) {
    died('We are sorry, but there appears to be a problem with the form you submitted.');
}


$email = $_POST['logMail']; // required

$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

if (!preg_match($email_exp, $email)) {
    $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}

function randomPassword()
{
    $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
    for ($i = 0; $i < 8; $i++) {
        $n = rand(0, $alphaLength);
        $pass[] = $alphabet[$n];
    }
    return implode($pass); //turn the array into a string
}


function sendPSW()
{
    $pass = randomPassword();
    $email = $_POST['logMail'];
    $newpsw = password_hash($pass, PASSWORD_DEFAULT);

    // create PDO connection object
    $dbConn = new DatabaseConnection();
    $pdo = $dbConn->getConnection();

    try {
        $statement = $pdo->prepare("SELECT * FROM `users` WHERE email = :email LIMIT 1");
        $statement->bindParam(':email', $email);
        $statement->execute();

        $result = $statement->fetchAll(PDO::FETCH_ASSOC);

        // no user matching the email
        if (empty($result)) {
            $_SESSION['error_message'] = 'Invalid email!';
            echo "WRONG EMAIL";
            return;
        }
            $sql = "UPDATE users SET password=:$newpsw WHERE email = :email";

            // Prepare statement
            $stmt = $pdo->prepare($sql);

            // execute the query
            $stmt->execute();


            if ($stmt->query($sql) === TRUE) {
                echo "Record updated successfully";
                $subject = "Password Update Request";
                $mailContent = 'Dear Customer, 
            <br/>Sending your randomly generated password, make sure you change it once logged in.
            <br/>Here is your temporary password: ' . $pass . '
            <br/><br/>Regards,
            <br/>eSHOP';
                //set content-type header for sending HTML email
                $headers = "MIME-Version: 1.0" . "\r\n";
                $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
                //additional headers
                $headers .= 'From: eSHOP' . "\r\n";
                //send email
                mail($email, $subject, $mailContent, $headers);
                return true;
            } else {
                echo "Error updating record";
                die();

            }

    } catch (PDOException $e) {
        // usually this error is logged in application log and we should return an error message that's meaninful to user
        return $e->getMessage();
    }
}
       }
       sendPSW();

【问题讨论】:

  • @chris85 你能告诉我如何绑定和进行静态绑定吗,我很困惑
  • “我是初学者” ...$newpsw = password_hash($pass, PASSWORD_DEFAULT);
  • 不要使用正则表达式来验证电子邮件。PHP 有一个 FILTER_VALIDATE_EMAIL 选项可与函数 filter_var 一起使用...
  • 以纯文本形式发送密码绝不是一个好主意。让他们直接在您的网站上更改它并向他们发送确认令牌,并且只有在您收到确认令牌后才在您的数据库中更改它。

标签: php mysql pdo prepared-statement


【解决方案1】:

此语句正在构建参数化查询,就像您在其他地方所做的一样;但它应该具有密码占位符的静态值。所以

$sql = "UPDATE users SET password=:$newpsw WHERE email = :email";

应该是:

$sql = "UPDATE users SET password=:newpsw WHERE email = :email";

然后execute 需要定义绑定:

// Prepare statement
$stmt = $pdo->prepare($sql);
// execute the query
$update_status = $stmt->execute(array(':newpsw' => $newpsw, ':email' => $email));

然后从$stmt-&gt;query($sql) 中删除query() 调用,因为这将重新执行查询,而query() 将不适用于参数化查询(无论如何都不应该与用户提供的数据一起使用。最好始终使用prepareexecute)。检查 $update_status 是否为 TRUE,并且您的查询应该有效。

【讨论】:

  • 这很好,但我不会称之为静态绑定;这意味着 PHP 中的其他内容。只是普通绑定或变量绑定更好。
  • 是的,没错 - 只是 static 的使用在这种情况下可能会造成混淆。
  • @Synchro 好的,我已将其删除并重新措辞以避免混淆。
猜你喜欢
  • 2023-03-29
  • 2017-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-21
  • 1970-01-01
相关资源
最近更新 更多