How can one handle forgotten passwords and allow users to request a new one via email in PHP?
To handle forgotten passwords and allow users to request a new one via email in PHP, you can create a "Forgot Password" functionality that prompts users to enter their email address. Upon submission, a unique token can be generated and stored in the database linked to the user's email. An email containing a link with the token can then be sent to the user, allowing them to reset their password.
<?php
// Check if form is submitted
if(isset($_POST['submit'])){
// Get user input
$email = $_POST['email'];
// Generate a unique token
$token = md5(uniqid(rand(), true));
// Store token in the database linked to the user's email
// Send email with link containing the token to reset password
$reset_link = "http://example.com/reset_password.php?token=".$token;
$message = "Click the following link to reset your password: ".$reset_link;
mail($email, "Password Reset", $message);
// Display success message to the user
echo "An email with instructions to reset your password has been sent to your email address.";
}
?>