admin posted: " One very important feature of any good membership website is a password reset system because some users are bound to forget their password. In this tutorial, I outline the steps involved in recovering a user's password; we will also be implementing such "
One very important feature of any good membership website is a password reset system because some users are bound to forget their password. In this tutorial, I outline the steps involved in recovering a user's password; we will also be implementing such a system using PHP and a MySQL database in this tutorial.
The whole process of implementing such a system can be broken down into 3 main steps. To ease the explanation, let's analyze these steps in terms of the forms that we will present for the user to fill:
Login Form: This form takes the username and password combination of a user and logs them in if they are registered on the system. On this form we provide a "Forgot your password?" link in case the user forgot their password and need to reset it.
Email Form: If the user has forgotten their password, they can click on the "Forgot your password?" link on the login page to reset it. Clicking on this link will take them to another page that prompts them to enter the email. When the email address they provide is not in our users table in the database, we will display and error message which says "No such user exists on our system". If on the other hand the user exists, we will generate a unique token (a unique random string) and store this token together with that email address in the password_resets table in the database. Then we will send them an email that has that token in a link. When they click on the link in the email we sent them, they will be sent back to our website on a page that presents them with another form.
New password Form: Once the user is back on our website again, we will grab the token that comes from the link and store it in a session variable. Then we will present them with a form that asks them to enter a new password for their account on our website. When the new password is submitted, we will query the password_resets table for the record that has that token that just came from the link in the mail. If the token is found on the password_resets table, then we are confident that they user is who they are and they clicked on the link in their mail. At this point now we grab the user's email from the password_resets (remember we had saved the token alongside their email address) table and use that email fetch the user from the users table and update their password.
Hope that's clear enough. If not then just stick around and it will become clearer as we implement.
Implementation
Create a database called password_recovery and in that database, create two tables namely users and password_resets with the following fields:
+----+-----------+--------------+------------+ | field | type | specs | +----+-----------+--------------+------------+ | id | INT(11) | | | email | VARCHAR(255) | | | token | VARCHAR(255) | UNIQUE | +----------------+--------------+------------+
Note: This application requires that the user already be registered on the system. But, we won't be covering the user registration part in this tutorial because it has already been covered on this site. You can follow that tutorial first (I recommend you do) or not, but keep in mind that we need to have a user in our users table in the database before we can proceed to reset their password. So one way or the other, add a user to your mysql database. You may use a tool like PHPMyAdmin and make sure you encrypt the password using md5().
Now create a project folder called password-recovery and make sure this folder is in your server directory (htdocs folder or www folder). In that folder, create three files namely: login.php, enter_email.php, new_pass.php:
Each of these three files represent the three steps we outlined earlier. Open each of them and paste the following codes in them:
In each of these files, you see that we are including three files which we haven't yet created, namely the app_logic.php , messages.php,file and main.css. The first handles all the logic of our application such as querying the database, sending email to user and more; the second displays feedback messages to the user such as when they enter a wrong email, the third is the styling of the application.
Create these files in the password-recovery folder. In the main.css file, add this styling code:
<?php session_start(); $errors = []; $user_id = ""; // connect to database $db = mysqli_connect('localhost', 'root', '', 'password-reset-php'); // LOG USER IN if (isset($_POST['login_user'])) { // Get username and password from login form $user_id = mysqli_real_escape_string($db, $_POST['user_id']); $password = mysqli_real_escape_string($db, $_POST['password']); // validate form if (empty($user_id)) array_push($errors, "Username or Email is required"); if (empty($password)) array_push($errors, "Password is required"); // if no error in form, log user in if (count($errors) == 0) { $password = md5($password); $sql = "SELECT * FROM users WHERE username='$user_id' OR email='$user_id' AND password='$password'"; $results = mysqli_query($db, $sql); if (mysqli_num_rows($results) == 1) { $_SESSION['username'] = $user_id; $_SESSION['success'] = "You are now logged in"; header('location: index.php'); }else { array_push($errors, "Wrong credentials"); } } } /* Accept email of user whose password is to be reset Send email to user to reset their password */ if (isset($_POST['reset-password'])) { $email = mysqli_real_escape_string($db, $_POST['email']); // ensure that the user exists on our system $query = "SELECT email FROM users WHERE email='$email'"; $results = mysqli_query($db, $query); if (empty($email)) { array_push($errors, "Your email is required"); }else if(mysqli_num_rows($results) <= 0) { array_push($errors, "Sorry, no user exists on our system with that email"); } // generate a unique random token of length 100 $token = bin2hex(random_bytes(50)); if (count($errors) == 0) { // store token in the password-reset database table against the user's email $sql = "INSERT INTO password_reset(email, token) VALUES ('$email', '$token')"; $results = mysqli_query($db, $sql); // Send email to user with the token in a link they can click on $to = $email; $subject = "Reset your password on examplesite.com"; $msg = "Hi there, click on this <a href=\"new_password.php?token=" . $token . "\">link</a> to reset your password on our site"; $msg = wordwrap($msg,70); $headers = "From: info@examplesite.com"; mail($to, $subject, $msg, $headers); header('location: pending.php?email=' . $email); } } // ENTER A NEW PASSWORD if (isset($_POST['new_password'])) { $new_pass = mysqli_real_escape_string($db, $_POST['new_pass']); $new_pass_c = mysqli_real_escape_string($db, $_POST['new_pass_c']); // Grab to token that came from the email link $token = $_SESSION['token']; if (empty($new_pass) || empty($new_pass_c)) array_push($errors, "Password is required"); if ($new_pass !== $new_pass_c) array_push($errors, "Password do not match"); if (count($errors) == 0) { // select email address of user from the password_reset table $sql = "SELECT email FROM password_reset WHERE token='$token' LIMIT 1"; $results = mysqli_query($db, $sql); $email = mysqli_fetch_assoc($results)['email']; if ($email) { $new_pass = md5($new_pass); $sql = "UPDATE users SET password='$new_pass' WHERE email='$email'"; $results = mysqli_query($db, $sql); header('location: index.php'); } } } ?>
Here you see three blocks of if statements. These statements handle three actions namely user login, receiving reset email and receiving new password. In the second block, after receiving the user email address, the user is being redirected to a pending.php page. This page simply displays a message telling the user that an email has been sent to their email address which they can use to reset their password.
Create pending.php in the root folder of our project and add this code inside it:
pending.php:
<?php include('app_logic.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Password Reset PHP</title> <link rel="stylesheet" href="https://www.code4example.com/php/php-reset-password-example/main.css"> </head> <body> <form class="login-form" action="login.php" method="post" style="text-align: center;"> <p> We sent an email to <b><?php echo $_GET['email'] ?></b> to help you recover your account. </p> <p>Please login into your email account and click on the link we sent to reset your password</p> </form> </body> </html>
messages.php is a file that holds the code snippet for displaying error messages on the form. Open it up and paste this code inside it:
Now open this project up on your browser at http://localhost/password-recovery/login.php and play with it.
Note: We used PHP's mail() function to send email to user. This function cannot send mails from localhost. It can only do so using a server that is hosted on the internet. However we can use a test mail application to simulate the sending of emails if you want to have a demo on your local system.
Conclusion
Thank you for following this tutorial to the end. I hope the explanation was clear enough and you learned something that can be of help to you in you web development. If you have any issues or concerns, don't forget to drop them in the comments below and I'll get to you.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.