Current Location: Home> Latest Articles> Complete Guide and Code Examples for Implementing Password Reset Email with PHP

Complete Guide and Code Examples for Implementing Password Reset Email with PHP

M66 2025-07-09

The Importance of Password Reset Email Functionality

In modern web applications, password reset functionality is a crucial component to ensure user account security. Sending password reset links via email not only simplifies the process for users but also helps prevent unauthorized access. This article will guide you step-by-step on how to implement password reset email functionality using PHP and provide ready-to-use code examples.

Steps to Implement Password Reset Email Feature

The key steps involved are as follows:

User Submits Password Reset Request

When a user forgets their password, they need to enter their registered email address on a page and click a button to send the password reset email.

Validate Email Address

After receiving the request, the backend should validate the format of the email and check whether it exists in the database.

Generate Unique Token and Store It

Once the email is validated, the system generates a unique password reset token and stores it in the database linked to the user’s email for future verification.

Send Password Reset Email

Use PHP mail functionality to send an email containing the password reset link with the token included, ensuring the link is unique and secure.

Handle Password Reset Request

When the user clicks the link in the email, the backend parses and validates the token from the database. If valid, redirect the user to the password reset form.

User Inputs New Password

On the password reset form, the user enters and confirms the new password. The backend verifies the inputs match and meet password strength requirements.

Update Password and Invalidate Token

After successful validation, update the user’s password in the database and remove the token to prevent reuse and ensure security.

PHP Code Example

<?php
// Send password reset email
function sendPasswordResetEmail($email, $token) {
    $subject = 'Password Reset';
    $message = 'Please click the link below to reset your password:';
    $message .= '<a href="http://your-domain.com/reset-password.php?token=' . $token . '">Reset Password</a>';
    // Send email
    $headers = 'Content-type: text/html; charset=UTF-8';
    mail($email, $subject, $message, $headers);
}

// Handle password reset request
function handlePasswordResetRequest($token) {
    global $db; // Make sure database connection is established
    $query = "SELECT * FROM users WHERE reset_token = '" . mysqli_real_escape_string($db, $token) . "'";
    $result = mysqli_query($db, $query);
    if (mysqli_num_rows($result) == 1) {
        // Token matched successfully, redirect to reset page
        header("Location: reset-password-form.php?token=" . urlencode($token));
        exit();
    } else {
        echo "Invalid token!";
    }
}

// Update user password
function updatePassword($token, $newPassword) {
    global $db; // Make sure database connection is established
    $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
    $query = "UPDATE users SET password = '" . mysqli_real_escape_string($db, $hashedPassword) . "', reset_token = NULL WHERE reset_token = '" . mysqli_real_escape_string($db, $token) . "'";
    mysqli_query($db, $query);
}

// Handle password reset form submission
function handlePasswordResetForm() {
    $newPassword = $_POST['new_password'];
    $confirmPassword = $_POST['confirm_password'];
    $token = $_POST['token'];

    if ($newPassword !== $confirmPassword) {
        echo "The two passwords do not match!";
    } else {
        updatePassword($token, $newPassword);
        echo "Password has been reset!";
    }
}

// Main logic handler
if (isset($_GET['token'])) {
    handlePasswordResetRequest($_GET['token']);
} elseif (isset($_POST['submit'])) {
    handlePasswordResetForm();
}
?>

Tips

Adjust the code as needed, especially the mail sending part where correct SMTP configuration is required to ensure email delivery. Additionally, to enhance security, consider encrypting the token and setting an expiration time to prevent misuse.

Summary

With the above explanations and code examples, you can build a fully functional and secure PHP password reset email system to improve user experience and protect account security.