On this page, the user will enter their email and from that, the code will first check if the email exists in the database. If the email exists, the code should generate a new password and send it to the user's email. In addition, the database tables: passwordreset should insert a record of the user's password reset action as well as update the user's account info so that they can log in with the new password. When I enter a valid email account to check, the form submits but the user's info table or passwordreset table are not updated. I'm not sure where the issue is. A little insight will be helpful.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>User Account Password Reset</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<div class="container" style="margin-top: 100px;">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3" align="center">
<div class="border border-primary" style="padding: 80px;">
<h2>Reset Password</h2><br>
<form method ="post" action="forgotpassword.php">
<input class="form-control" id="email" type="email" placeholder="Your email address..."><br>
<input class="btn btn-primary form-control" type="submit" value="Reset Password"><br>
</form><br><br>
<p id="response"></p>
</div>
</div>
</div>
</div>
</body>
</html>
PHP: resetpassword.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
include('functions.php');
if(isset($_POST['submit'])){
$con = new mysqli('localhost','root','','db_dom');
$email = $_POST['email'];
//check if email entered is in DB
$sql = $con->query("SELECT email FROM usr_t WHERE email='$email'");
if ($sql->num_rows > 0) {
//Generate new hashed password
$newPassword = generateRandomString();
$newPasswordHash = password_hash($newPassword, PASSWORD_BCRYPT);
require_once "PHPMailer/PHPMailer.php";
require_once "PHPMailer/Exception.php";
$mail = new PHPMailer();
$mail->addAddress($email);
$mail->setFrom("support@webdominator.com", "Web Dominator");
$mail->Subject = "User Account Password Recovery";
$mail->Body = "
Greetings,<br><br>
We are pleased to inform you that your password recovery is successful.<br>
Your new password is: " . $newPassword . "<br>If you didnt not request a recovery of your account password, please go to your account and change tyour password immediately. Thank you!<br><br>
Kind Regards,<br><br>
Support.";
if ($mail->send()) {
//insert record into account password reset table
$time = date("Y-m-d H:i:s");
$sql = "INSERT INTO passwordreset(id, user, time_reset) VALUES ('', '$email', '$time')";
$con->query($sql);
//update user table with new hashed password
$con->query("UPDATE usr_t SET password = '$newPasswordHash' WHERE email = '$email'");
echo '<div class="alert alert-success">Please check your email inbox</div>';
} else {
echo '<div class="alert alert-danger">Something went wrong! Please try again.</div>';
}
} else {
echo '<div class="alert alert-danger">Sorry! Email not found</div>';
}
}
?>
functions.php
function generateRandomString(){
$str = "QWERTYZXCVASDLKMBJFOPTMSV1234567890";
$str = str_shuffle($str);
$str = substr($str, 0, 10);
return $str;
}
ANSWER: I didn't know what the issue was but I decided to try it another way using ajax code for the submit and changed a few lines. Now my code works and users can receive an email after going through the necessary verifications i.e. is the email valid?. Here's the final code:
forgotpassword.php:
<?php
use PHPMailer\PHPMailer\PHPMailer;
include('functions.php');
if(isset($_POST['email'])){
$con = new mysqli('localhost','root','','pd.com');
$email = $con->real_escape_string($_POST['email']);
//check if email entered is in DB
$sql = $con->query("SELECT email FROM usr_t WHERE email='$email'");
if ($sql->num_rows > 0) {
$newPassword = generateRandomString();
$newPasswordHash = password_hash($newPassword, PASSWORD_BCRYPT);
require_once "PHPMailer/PHPMailer.php";
require_once "PHPMailer/Exception.php";
$mail = new PHPMailer();
$mail->addAddress($email);
$mail->setFrom("support@pd.com", "PD");
$mail->Subject = "Account Password Recovery";
$mail->isHTML(true);
$mail->Body = "
Greetings,<br><br>
We are pleased to inform you that your password recovery is successful.<br><br>
Your new password is: ".$newPassword."<br><br>If you didnt not request a recovery of your account password, please go to your account and change your password immediately. Thank you!<br><br>
Kind Regards,<br><br>
Support.";
if ($mail->send()) {
//insert record into account password reset table
$sql = "INSERT INTO `passwordreset` (`id`, `user`, `time_reset`) VALUES (NULL, '$email', current_timestamp())";
$con->query($sql);
//update user table with new hashed password
$con->query("UPDATE usr_t SET password = '$newPasswordHash' WHERE email = '$email'");
exit(json_encode(array("status" => 1, "msg" => 'Please check your email inbox!')));
} else {
exit(json_encode(array("status" => 0, "msg" => 'Something went wrong!')));
}
} else {
exit(json_encode(array("status" => 0, "msg" => 'Sorry! Email not found!')));
}
}
?>
HTML PAGE:
<!DOCTYPE html>
<html lang="en">
<head>
<title>User Account Password Reset</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<!-- Reset Password Form -->
<div class="container" style="margin-top: 100px;">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3" align="center">
<div class="border border-primary" style="padding: 80px;">
<h2>Reset Password</h2><br>
<label>Enter your email address: </label>
<input class="form-control" id="email" placeholder="Your Email Address..."><br>
<input type="button" class="btn btn-primary form-control" value="Reset Password">
<br><br>
<p id="response"></p>
</div>
</div>
</div>
</div>
<script
src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script type="text/javascript">
var email = $("#email");
$(document).ready(function () {
$('.btn-primary').on('click', function () {
if (email.val() != "") {
email.css('border', '1px solid green');
$.ajax({
url: 'forgotpassword.php',
method: 'POST',
dataType: 'json',
data: {
email: email.val()
}, success: function (response) {
if (!response.success)
$("#response").html(response.msg).css('color', "green");
else
$("#response").html(response.msg).css('color', "red");
}
});
} else {
email.css('border', '1px solid red');
}
});
});
</script>
</body>
</html>