Secure and Simple: Forgot Password in PHP

Forgot Password in PHP

how to create a forgot password in php and send via email

This form has an input field for the user’s email address and a submit button. When the user submits the form, it sends a POST request to the forgot-password.php file specified in the action attribute.

<!-- forgot-password-form.html -->

<!DOCTYPE html>
<html>
<head>
  <title>Forgot Password</title>
</head>
<body>
  <h1>Forgot Your Password?</h1>
  <p>Please enter your email address to receive a verification code to reset your password.</p>
  <form method="post" action="forgot-password.php">
    <label for="email">Email address:</label>
    <input type="email" id="email" name="email" required>
    <button type="submit">Send Verification Code</button>
  </form>
</body>
</html>

In this code, we first check if the form was submitted using $_SERVER['REQUEST_METHOD']. If it was, we retrieve the user’s email from the $_POST data.

Then, we connect to the database using mysqli and prepare an SQL query to retrieve the user with this email. We execute the query and check if there is exactly one row returned, indicating that the user exists in the database.

If there is one row, we generate a random verification code to use as the password reset link and update the user’s verification code and expiration time in the database. Then, we send an email to the user with the verification code using the mail() function. If the email is sent successfully, we display a success message. If there is no user with this email in the database or there was an error sending the email, we display an error message.

code in PHP for forgot password checking if the email exists in the database and sending a verification code to reset the password:

// forgot-password.php

// First, let's check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Retrieve the user's email from the form data
  $email = $_POST['email'];

  // Connect to the database
  $servername = "localhost";
  $username = "your_username";
  $password = "your_password";
  $dbname = "your_database_name";

  // Create connection
  $conn = new mysqli($servername, $username, $password, $dbname);

  // Check connection
  if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
  }

  // Prepare SQL query to retrieve the user with this email
  $sql = "SELECT * FROM users WHERE email='$email'";

  // Execute the query
  $result = $conn->query($sql);

  // Check if there is a user with this email in the database
  if ($result->num_rows == 1) {
    // The email exists in the database, so we can proceed with resetting the password
    // Generate a random verification code to use as the password reset link
    $verification_code = rand(1000, 9999);

    // Update the user's verification code and expiration time in the database
    $expire = date('Y-m-d H:i:s', strtotime('+1 hour'));
    $update_sql = "UPDATE users SET verification_code='$verification_code', verify_expire='$expire' WHERE email='$email'";
    $conn->query($update_sql);

    // Send an email to the user with the verification code
    $to = $email;
    $subject = 'Password Reset Verification Code';
    $message = "Your Password Reset Verification Code: $verification_code";
    $headers = 'From: webmaster@example.com' . "\r\n" .
               'Reply-To: webmaster@example.com' . "\r\n" .
               'X-Mailer: PHP/' . phpversion();

    if (mail($to, $subject, $message, $headers)) {
      // The email was sent successfully
      echo "A verification code has been sent to your email address.";
    } else {
      // There was an error sending the email
      echo "There was an error sending the verification code, please try again later.";
    }
  } else {
    // There is no user with this email in the database
    echo "No user found with this email address.";
  }

  // Close the database connection
  $conn->close();
}

This form includes three input fields: one for the verification code, and two for the new password. The required attribute on each field ensures that the user must fill in all three fields before submitting the form.

The form’s action attribute points to the PHP script that we created earlier (reset-password.php). When the user submits the form, the script will execute and process the data. If there are any errors (such as an invalid verification code or non-matching passwords), an error message will be displayed at the top of the page. Otherwise, if the password reset is successful, the user will be redirected to a confirmation page.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Reset Password</title>
  </head>
  <body>
    <h1>Reset Password</h1>
    <?php if (isset($error)): ?>
      <p style="color: red;"><?php echo $error ?></p>
    <?php endif; ?>
    <form action="reset-password.php" method="POST">
      <label for="code">Verification Code:</label>
      <input type="text" name="code" id="code" required>
      <br>
      <label for="new-password">New Password:</label>
      <input type="password" name="new-password" id="new-password" required>
      <br>
      <label for="confirm-password">Confirm Password:</label>
      <input type="password" name="confirm-password" id="confirm-password" required>
      <br>
      <input type="submit" value="Reset Password">
    </form>
  </body>
</html>

In this version, after retrieving the verification code from the form, we execute an SQL query to select a row from a codes table that matches the specified code. We bind the $code variable to the :code parameter and then execute the query using PDOStatement::execute() method.

If the query returns zero rows (i.e., no matching codes were found), we output an error message and exit the script using exit() function.

<?php
// reset-password.php

// Check if the form has been submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

  // Retrieve the verification code and new password from the form
  $code = $_POST['code'];
  $newPassword = $_POST['new-password'];
  $confirmPassword = $_POST['confirm-password'];

  // TODO: Validate the verification code from the database
  $dsn = 'mysql:host=localhost;dbname=your_database_name';
  $username = 'your_username';
  $password = 'your_password';

  try {
    $db = new PDO($dsn, $username, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $db->prepare("SELECT * FROM codes WHERE code=:code");
    $stmt->bindParam(":code", $code);
    $stmt->execute();
    
    if ($stmt->rowCount() == 0) {
      // Invalid verification code
      echo "<p style='color: red;'>Invalid verification code. Please try again.</p>";
      exit();
    }
  } catch (PDOException $e) {
    echo "<p style='color: red;'>Error: " . $e->getMessage() . "</p>";
    exit();
  }
  
  // Validate the new password
  if ($newPassword != $confirmPassword) {
    // Passwords do not match
    echo "<p style='color: red;'>New passwords do not match. Please try again.</p>";
    exit();
  }

  // TODO: Update the user's password in the database
  try {

    // Assume the user_id is passed in as a session variable or parameter
    $user_id = $_SESSION['user_id']; // Change this to your actual session variable name or parameter name
    $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);

    $stmt = $db->prepare("UPDATE users SET password=:password WHERE id=:id");
    $stmt->bindParam(":password", $hashedPassword);
    $stmt->bindParam(":id", $user_id);
    $stmt->execute();

  } catch (PDOException $e) {
    echo "<p style='color: red;'>Error updating password: " . $e->getMessage() . "</p>";
    exit();
  }
  
  // Redirect the user to a confirmation page
  header('Location: password-updated.php');
  exit();
}
?>

Our Recommendation

Avatar of Akhand Pratap Singh

Akhand Pratap Singh

Greetings and a warm welcome to my website! I am Akhand Pratap Singh, a dedicated professional web developer and passionate blogger.

Related Post

Leave a Comment





Newsletter

Subscribe for latest updates

We don't spam.

Loading

Categories