How can PHP developers securely handle forgotten passwords without decrypting them?

When a user forgets their password, it is not secure to send them their original password as it should be stored securely hashed in the database. Instead, developers can generate a unique, time-limited token for password reset requests. This token can be securely stored in the database and sent to the user via email. When the user clicks on the link with the token, they can then reset their password securely.

// Generate a unique token for password reset
$token = bin2hex(random_bytes(16));

// Store the token in the database with the user's email
$query = "INSERT INTO password_reset_tokens (email, token, created_at) VALUES (?, ?, NOW())";
$stmt = $pdo->prepare($query);
$stmt->execute([$email, $token]);

// Send the token to the user via email with a link to reset their password
$emailBody = "Click the following link to reset your password: https://example.com/reset_password?token=$token";
mail($email, "Password Reset Request", $emailBody);