Hello Devs, first appears in codexpress labs facebook like Forgotten Password script using PHP, MSQLI, CSS AND HTML, this tutorial is centred on social network developers who want to implement forgot password system on their website (forum etc). This tutorial is requested by codexpress labs user.
This system will send a verification code through email to the registered user email address used during registration, and providing a second level authentication allowing the user to confirm the code to reset password, if any user pass this level then the system will allow the user to change or create new password.
Without wasting much of time let rock and roll to the upside of programming, follow the steps you will just do great.
Check out previous article on forget password system
REQUIREMENT
Knowledge of Basic PHP and MySqli
We are going to create 5 php page
index.php
account-verify.php
code-verify.php
account-login.php
reset-password.php
DATABASE SCHEME
-- -- Table structure for table `users` -- CREATE TABLE `users` ( `uid` int(11) NOT NULL, `avatar` varchar(1000) NOT NULL, `username` varchar(20) NOT NULL, `password` varchar(1000) NOT NULL, `phone` varchar(15) NOT NULL, `fname` varchar(20) NOT NULL, `lname` varchar(20) NOT NULL, `email` varchar(500) NOT NULL, `gender` varchar(10) NOT NULL, `passreset` varchar(300) NOT NULL, `reg_date` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`uid`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `uid` int(11) NOT NULL AUTO_INCREMENT;COMMIT;
STEP 1
What we do on this page is to verify our user table if at all there is a user account attached to the entered email address or phone, if all validation passed redirect the user to account-verify.php to see if it is actually his/her account.
Copy the following code to index.php file.
<!DOCTYPE html> <html> <head> <title>Forgot Password - Codexpress</title> </head> <body> <div style="margin-left: 10px; text-align: center; "><a href="index.php"><h1 style="font-size:150%; font-weight: bolder; color:#47c9af "><img src="img/hplogo.png" style="width: 10%"> <?php echo APPNAME;; ?></h1></a> <p>Please enter your email address or phone number to search for your account.</p> <?php if(isset($_POST['forget_pass'])){ $email = $_POST['email']; //Storing email in $email variable. $match = $db->query("SELECT * FROM users WHERE email='$email' OR phone='$email' "); if(mysqli_num_rows($match)!=0) // if user exist { $row=mysqli_fetch_assoc($match); $db_email = $row['email']; $db_phone = $row['phone']; $db_avatar = $row['avatar']; $db_fname = $row['fname']; $db_uid = encrypt($row['uid']); echo '<script type="text/javascript">window.location = "account-verify.php?sid='.$db_uid.'&sesson_log='.session_id().'"; </script>'; // redirect } else { echo '<p style="font-size: 1.05em; margin-right: 0px; margin-bottom: 15px; margin-left: 0px; padding-left: 10px; border-left: 3px solid darkred; color: rgb(37, 37, 37);text-align: justify; color:darkred; font-weight: bold; line-height: 21px;">Oops! sorry we couldn\'n find your account found!</p>'; // show error message } } echo ' <form id="signin_form" class="Form" accept-charset="utf-8" action="?try-again" method="post" style="margin-top: 0;"> <div class="form-group"> <input type="text" class="form-control" name="email" placeholder="Email Address or phone number"> </div> <button type="submit" name="forget_pass" class="btn btn-azure">» Submit</button> <a href="index.php" class="btn btn-default">» Cancel</a> </form>'; // and show form again ?> <p></p> <small><a href="help.php?ask=access+to+my+email">Don't have access to my email</a> - <a href="help.php?ask=access+to+my+phone">Don't have access to my phone number</a> </small> <hr class="style-eight"> <p align="center"><a href="index.php" class="btn-group-justified btn btn-success">» Log in</a></p> </div> </body> </html>
STEP 2
After the user is confirmed and redirected, options are given How the user would want to receive the code to reset password, either by phone number or email addresseither is ok but this tutorial is centred on EMAIL using PHPMail() function.`
Six (6) digit unique random numbers are generated from the system and attached to each user account during password recovery, using php rand() function;
After that and email is sent to user email address containing the code to create new password, redirected to code-verify.php to confirm emailed code.
<!DOCTYPE html> <html> <head> <title>Forgot Password - Codexpress</title> </head> <body> <div style="margin-left: 10px; text-align: center; "><a href="index.php"><h1 style="font-size:150%; font-weight: bolder; color:#47c9af "><img src="img/hplogo.png" style="width: 10%"> <?php echo APPNAME;; ?></h1></a> <?php if (isset($_REQUEST['sid'])) { $sid=(decrypt($_REQUEST['sid'])); $hashlogin=($_REQUEST['sid']); $match = $db->query("SELECT * FROM users WHERE uid='$sid'"); $mysql_num_rows = mysqli_num_rows($match); if(mysqli_num_rows($match)!=0) { $row=mysqli_fetch_assoc($match); $db_email = $row['email']; $db_phone = $row['phone']; $db_avatar = $row['avatar']; $db_fname = $row['fname']; $db_lname = $row['lname']; $db_uid = ($row['uid']); //echo $db_uid; if (isset($_POST['send'])) { $id=(decrypt($_REQUEST['id'])); $hashcode=($_REQUEST['id']); //echo "$id"; $match1 = $db->query("SELECT * FROM users WHERE phone='$id' OR email='$id'"); if(mysqli_num_rows($match1)!=0) // check if user exist { $row1=mysqli_fetch_assoc($match1); $db_email1 = $row1['email']; $db_phone1 = $row1['phone']; $db_fname1 = $row1['fname']; $db_uid1 = ($row1['uid']); $passreset = ($row1['passreset']); $code = rand(10000,1000000); // auto generate unique code if ($db_email1==$id) { # code... /* Send a link to email address */ $to = $db_email1; $subject = 'Verifucation Code'; $from = 'admin@hpsocial.com'; // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Create email headers $headers .= 'From: '.$from."\r\n". 'Reply-To: '.$from."\r\n" . 'X-Mailer: PHP/' . phpversion(); // php version if ($passreset) { // Compose a simple HTML email message $message = '<html><body>'; $message .= '<h1 style="color:#f40;">Hi '.$db_fname1.'!</h1>'; $message .= '<p style="color:#080;font-size:18px;">VERIFICATION CODE: '.$passreset.'</p>'; $message .= '</body></html>'; } else { // Compose a simple HTML email message $message = '<html><body>'; $message .= '<h1 style="color:#f40;">Hi '.$db_fname1.'!</h1>'; $message .= '<p style="color:#080;font-size:18px;">VERIFICATION CODE: '.$code.'</p>'; $message .= '</body></html>'; } // Sending email if(mail($to, $subject, $message, $headers)){ echo 'Your mail has been sent successfully.'; } else{ echo 'Unable to send email. Please try again.'; } $db->query("UPDATE users SET passreset ='$code' WHERE email='$id' OR phone='$id'"); // set unique t user account echo '<script type="text/javascript">window.location = "code-verify.php?code='.$hashcode.'&sesson_log='.session_id().'"; </script>'; // redirect } elseif ($db_phone1==$id) { # code... echo '<script type="text/javascript">alert("Application in progress...");</script>'; // for phone service // API_LINK goes here } } } ?> <form action="" method="post"> <table class="table"> <tr> <th scope="col"><?php echo $db_fname.' '.$db_lname; ?><br> <small><?php echo APPNAME; ?> user</small> </th> <th scope="col"><img class="img-responsive" style="width:90px; " src="img/avatars/<?php if(empty($db_avatar)){echo 'avatar.jpg';}else echo $db_avatar; ?>" alt="<?php echo $db_fname; ?>"></th> </tr> </table> <p>How do you want to receive the code to reset your password?</p> <table class="table"> <tr> <th scope="col">Send code via SMS <br>+******************<?php echo substr($db_phone, -2); ?></th> <th scope="col"> <div class="maxl"> <label class="radio inline"> <input type="radio" name="id" value="<?php echo encrypt($db_phone); ?>"> <span> </span> </label> </div> </th> </tr> <tr> <th scope="col">Send code via email<br> <?php echo substr($db_email, 0,2); ?>******************<?php echo substr($db_email, -10); ?></th> <th scope="col"> <div class="maxl"> <label class="radio inline"> <input type="radio" name="id" value="<?php echo encrypt($db_email); ?>" checked> <span> </span> </label> </div> </th> </tr> </table> <div class="center"> <button type="submit" name="send" class="btn btn-group-justified btn-azure">» Continue</button> </div> </form> <?php //echo '<script type="text/javascript">window.location = "account-verify.php?sid='.$db_uid.'&sesson_log='.session_id().'"; </script>'; } else { echo '<p style="font-size: 1.05em; margin-right: 0px; margin-bottom: 15px; margin-left: 0px; padding-left: 10px; border-left: 3px solid darkred; color: rgb(37, 37, 37);text-align: justify; color:darkred; font-weight: bold; line-height: 21px;">Oops! sorry we couldn\'n find your account found!</p>'; } } ?> <p></p> <p align="center"><a href="forgot.php" class="btn-group-justified btn btn-default">» Not my account</a></p> <hr class="style-eight"> <p align="center"><a href="account-login.php?sid=<?php echo($hashlogin); ?>&session_id=<?php echo session_id(); ?>" class="btn-group-justified btn btn-success">» Password to Log in</a></p> </div> </body> </html>
STEP 3
After code is confirmed, the is redirected to reset-password.php page to created fresh new password, all measures are taken to prevent account been hacked, breached and security reasons
Copy the following code to account-verify.php
<!DOCTYPE html> <html> <head> <title>Forgot Password - Codexpress</title> </head> <body> <p style="font-size: 1.05em; padding: 5px; background:rgb(0, 152, 247) ; border-left: 3px solid rgb(0, 152, 247); color: white;text-align: justify;">Enter verification code sent to you </p> <?php if (isset($_POST['resend_code'])) { $id=(decrypt($_REQUEST['code'])); echo "$id"; $match11 = $db->query("SELECT * FROM users WHERE phone='$id' OR email='$id'"); $mysql_num_rows = mysqli_num_rows($match11); if($mysql_num_rows!='0') { $row11=mysqli_fetch_assoc($match11); $db_email1 = $row11['email']; $db_phone1 = $row11['phone']; $db_fname1 = $row11['fname']; $db_uid1 = ($row11['uid']); $code = $row11['passreset']; # code... /* Send a registration link to entered email address */ $to = $db_email1; $subject = 'Verify Code'; $message = 'Your Verify Code '.$code.' '; $headers = 'From: No-reply@demo.com' . "\r\n" . 'Reply-To: No-reply@demo.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); // Sending email if(mail($to, $subject, $message, $headers)){ echo 'Your mail has been sent successfully, check your inbox.'; } else{ echo 'Unable to send email. Please try again.'; } } } if (isset($_REQUEST['code'])) { $vcode=(decrypt($_REQUEST['code'])); if (isset($_POST['verify_btn'])) { # code... $verifycode=($_POST['verifycode']); $hashcode=(encrypt($_POST['verifycode'])); $match = $db->query("SELECT * FROM users WHERE passreset='$verifycode'"); if(mysqli_num_rows($match)=='1') { echo '<script type="text/javascript">window.location = "reset-password.php?code='.$hashcode.'&sesson_log='.session_id().'"; </script>'; } else { echo '<p style="font-size: 1.05em; margin-right: 0px; margin-bottom: 15px; margin-left: 0px; padding-left: 10px; border-left: 3px solid darkred; color: rgb(37, 37, 37);text-align: justify; color:darkred; font-weight: bold; line-height: 21px;">Oops! Invalid verification code provided !</p>'; } } } ?> <form action="" method="post"> <div class="form-group"> <input type="text" class="form-control" name="verifycode" placeholder="Enter code"> <input type="hidden" name="resend_code"> </div> <div class="center"> <button type="submit" name="verify_btn" class="btn btn-group-justified btn-azure">» Submit</button> </div> <hr class="style-eight"> <div class="center"> <button type="submit" name="resend" class="btn btn-group-justified btn-success">» Don't receive code? re-send again</button> </div> </form> </body> </html>
STEP 4
This is the final stage where the user will be able to change or create new password for account.
Copy the following code below to reset-password.php
Copy the following code below to reset-password.php
<div style="margin-left: 10px; text-align: center; "><a href="index.php"><h1 style="font-size:150%; font-weight: bolder; color:#47c9af "><img src="img/hplogo.png" style="width: 10%"> Password Reset</h1></a> <?php if(@$_GET['code']) { $get_code = $_GET['code']; $get_code=(decrypt($_REQUEST['code'])); @$emailme = $_GET['email']; $query = $db->query("SELECT * FROM users WHERE passreset ='$get_code'"); $data = mysqli_fetch_assoc($query); $db_code = $data['passreset']; $db_uid = $data['uid']; if($db_code) { echo ' <form id="signin_form" class="Form" accept-charset="utf-8" action="" method="post" style="margin-top: 0;"> <label> <span>Enter New Password</span> </label> <div class="form-group"> <input type="password" class="form-control" required="required" minlength="5" name="password" placeholder="New Password"> </div> <label> <span>Retype New Password</span> </label> <div class="form-group"> <input type="password" class="form-control" required="required" minlength="5" name="password1" placeholder="Retype Password"> </div> <input name="code" value="'.$get_code.'" type="hidden"> <input name="uid" value="'.$db_uid.'" type="hidden"> <button type="submit" class="btn btn-azure">» Submit</button> </form>'; } } if(!empty($_POST['password']) && !empty($_POST['password1'])){ $password=htmlentities($_POST['password']); $password1=htmlentities($_POST['password1']); $password_hash=hash('sha256', $password); @$uid = $_POST['uid']; if($password == $password1) { $passup=$db->query("UPDATE users SET password ='".$password_hash."', passreset ='' WHERE uid='".$uid."'") ;; ?> <script> function Redirect() { window.location="<?php echo "index.php";?>" } document.write('<p align="center" style="background-color:#CFF;">Password updated !<br> Authormatically redirect in 5 sec.</p>'); setTimeout('Redirect()', 5000); </script> <?php }else { echo"<p align='center' style='background-color:#CFF;'>Password is not the same try again !</p>"; } } ?> <hr class="style-eight"> <p align="center"><a href="index.php" class="btn-group-justified btn btn-success">» Log In</a></p> </div>
account-login.php Code
<!DOCTYPE html> <html> <head> <title>Forgot Password - Codexpress</title> </head> <body> <?php // user registration script if (isset($_POST['account-log-in'])) { $username=trim(ucfirst($_POST['username'])); $password=htmlentities($_POST['password']); $password=hash('sha256', $password); # code... $checkU=$db->query("SELECT * FROM users WHERE username='$username' AND password='$password'"); $data=mysqli_fetch_assoc($checkU); $signed=$checkU->num_rows;; if ($signed) { $username=$data['username']; $fname=$data['fname']; $lname=$data['lname']; $email=$data['email']; $phone=$data['phone']; $uid=$data['uid']; $_SESSION['username'] = $username; // Initializing Session $_SESSION['fname'] = $fname; // Initializing Session $_SESSION['lname'] = $lname; // Initializing Session $_SESSION['email'] = $email; // Initializing Session $_SESSION['phone'] = $phone; // Initializing Session $_SESSION['uid'] = $uid; // Initializing Session //login success redirect //header("location: home.php"); echo '<script type="text/javascript">window.location = "home.php"; </script>'; } else { echo '<p style="font-size: 1.05em; margin-right: 0px; margin-bottom: 15px; margin-left: 0px; padding-left: 10px; border-left: 3px solid darkred; color: rgb(37, 37, 37);text-align: justify; color:darkred; font-weight: bold; line-height: 21px;"><span class="fa fa-info-circle"></span> Login details incoorrect please try again!</p>'; } } // verify log in account if (isset($_REQUEST['sid'])) { $sid=(decrypt($_REQUEST['sid'])); $match = $db->query("SELECT * FROM users WHERE uid='$sid'"); if(mysqli_num_rows($match)!=0) { $row=mysqli_fetch_assoc($match); $db_username = $row['username']; $db_phone = $row['phone']; $db_avatar = $row['avatar']; $db_fname = $row['fname']; $db_lname = $row['lname']; $db_uid = ($row['uid']); ?> <table class="table"> <tr> <th scope="col"><?php echo $db_fname.' '.$db_lname; ?><br> <small><?php echo APPNAME; ?> user</small> </th> <th scope="col"><img class="img-responsive" style="width:90px; " src="img/avatars/<?php if(empty($db_avatar)){echo 'avatar.jpg';}else echo $db_avatar; ?>" alt="<?php echo $db_fname; ?>"></th> </tr> </table> <form class="form" action="" method="post"> <input type="hidden" name="username" value="<?php echo($db_username); ?>"> <input type="password" class="form-control" name="password" placeholder="Enter password"> <p></p> <div class="center"> <button type="submit" name="account-log-in" class="btn btn-group-justified btn-azure">» Continue</button> </div> </form> <?php } } ?> </body> </html>
DATABASE CONNECTION
<?php @session_start(); define('DB_SERVER', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_DATABASE', 'hpsocial'); $prefix="ny_"; $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE); define('APPNAME', 'Codexpress'); ?>
Please like or share with friends and don’t forget say hello if you find it interesting, more are still coming to codexpress labs Devs users.
Hit me with a comment!