📘 Lesson  ·  Lesson 47

Forgot Password Reset

Forgot Password Reset

About

Forgot password lets users reset their password via a secure link emailed to them, using a random token.

Step 1: Create Reset Token

$email = $_POST["email"];
$token = bin2hex(random_bytes(32));   // secure random token
$stmt = $pdo->prepare("UPDATE users SET reset_token = ? WHERE email = ?");
$stmt->execute([$token, $email]);

$link = "https://site.com/reset.php?token=$token";
mail($email, "Reset password", "Click: $link");

Step 2: Reset with Token

$token = $_GET["token"];
$stmt = $pdo->prepare("SELECT id FROM users WHERE reset_token = ?");
$stmt->execute([$token]);
if ($user = $stmt->fetch()) {
    $hash = password_hash($_POST["new_password"], PASSWORD_DEFAULT);
    $pdo->prepare("UPDATE users SET password=?, reset_token=NULL WHERE id=?")
        ->execute([$hash, $user["id"]]);
    echo "Password reset!";
}

Summary

  • Email a secure random token; store it on the user row.
  • On reset, match the token, set the new hashed password, clear the token.

परिचय

Forgot password users को email किए secure link से password reset करने देता है, random token का use करके।

Step 1: Reset Token बनाएं

$email = $_POST["email"];
$token = bin2hex(random_bytes(32));   // secure random token
$stmt = $pdo->prepare("UPDATE users SET reset_token = ? WHERE email = ?");
$stmt->execute([$token, $email]);

$link = "https://site.com/reset.php?token=$token";
mail($email, "Reset password", "Click: $link");

Step 2: Token से Reset करें

$token = $_GET["token"];
$stmt = $pdo->prepare("SELECT id FROM users WHERE reset_token = ?");
$stmt->execute([$token]);
if ($user = $stmt->fetch()) {
    $hash = password_hash($_POST["new_password"], PASSWORD_DEFAULT);
    $pdo->prepare("UPDATE users SET password=?, reset_token=NULL WHERE id=?")
        ->execute([$hash, $user["id"]]);
    echo "Password reset!";
}

सारांश

  • Secure random token email करें; user row पर store करें।
  • Reset पर token match करें, नया hashed password set करें, token clear करें।
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।