我正在处理的作业(电子商务课程)要求我使用php为用户生成新密码,并向用户发送包含新密码的电子邮件。我成功生成了密码,使用php mail()从我学校的服务器发送电子邮件给自己(gmail帐户),但是代表密码的php变量始终为空。我一直在这里和其他网站寻找答案,但找不到我做错了什么。 我希望解决这个特殊问题,我不打算使用PHPMailer或其他替代方案。此外,我不打算讨论更安全的方式来发送电子邮件,或讨论加密,只是想讨论这个特定问题以及它为什么或不起作用。提前感谢您的任何建议。
if ($mysqli->conect_errno) {
die("Error: Could not connect to database." . $mysqli->connect_error);
} else {
echo "<p>Connected<br></p>";
}
$email = $_POST['email_input'];
try {
$password = reset_password($email, $mysqli);
notify_password($email, $password, $mysqli);
echo 'Your password has changed and has been emailed to you.<br>';
}
catch(Exception $e) {
echo 'Your password could not be reset';
}
function reset_password($email, $mysqli){
$new_password = randomString(8, 12);
if ($new_password == false) {
throw new Exception('could not generate new password');
}
$rand_number = rand(0, 999);
$new_password .= $rand_number;
echo "NEW PASSWORD: " .$new_password."\r\n";
$query = "UPDATE registration
SET password = sha1('".$new_password."')
WHERE email = '".$email."'";
$result = $mysqli->query($query);
if($result) {
echo "<br>Password Reset<br>";
}else {
echo "An error has occured";
}
}
function randomString($min_length, $max_length){
return substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), $min_length, $max_length);
}
function notify_password($email, $password, $mysqli){
$query = "SELECT email FROM registration WHERE email='".$email."'";
$result = $mysqli->query($query);
if(!$result){
throw new Exception('could not find email address');
}else if ($result->num_rows == 0) {
throw new Exception('Could not find email address:user not in database');
}else {
$row = $result->fetch_object();
$email = $row->email;
$from = "From support@HelpFinder \r\n";
$mesg = "Your password has been changed to ".$password."\r\n"."Please change it the next time you log in.\r\n";
if(mail($email, 'HelpFinder Login Information', $mesg, $from)) {
return true;
}else {
throw new Exception('Could not send email.');
}
}
}
答案 0 :(得分:0)
首先,请在if声明之前检查您是否有双$结果。
$result = $result = $mysqli->query($query);
之后,您可以尝试将var_dump设置为$ password变量,以检查它是否已正确传递给notify_password函数。您还可以发布$ password变量定义,以便我们更深入地检查。
答案 1 :(得分:0)
检查您是否正确发送$ password变量作为参数, 可能是空的