473,566 Members | 2,776 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How To Add Remember Me Feature With Cookies ?

39 New Member
Hi,

This is a login.php.

The user is given a choice to either input his/her Username & Password or Email & Password. In short, either log-in inputting your Username or your Email.
People are welcome to provide their own code samples in mysqli procedural or edit (fix) my code by adding comments and displaying it on this thread for all newbies to learn from. From your code and your code comments, I, aswell as other newbies would learn.
It is written in mysqli procedural. I have not learned pdo oop yet. I need help in the login.php to add the "Remember Me" feature using Cookies.
Can someone be the Great Samaritan here to show me an example ? You're welcome to not start from scratch but work on my work (login.php).
registration.ph p, logout.php and account_acivati on.php finished. Those last 3 files are working fine. Working on the home.php now.

login.php
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. /*
  4. ERROR HANDLING
  5. */
  6. declare(strict_types=1);
  7. ini_set('display_errors', '1');
  8. ini_set('display_startup_errors', '1');
  9. error_reporting(E_ALL);
  10. mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
  11.  
  12. include 'config.php';
  13.  
  14. // check if user is already logged in
  15. if (is_logged() === true) 
  16. {
  17.     //Redirect user to homepage page after 5 seconds.
  18.     header("refresh:2;url=home.php");
  19.     exit; //
  20. }
  21.  
  22.  
  23. if (isset($_POST["login_username_or_email"]) && isset($_POST["login_password"]))
  24.     {
  25.         $username_or_email = trim($_POST["login_username_or_email"]);
  26.         $password = $_POST["login_password"];        
  27.  
  28.         //Select Username or Email to check against Mysql DB if they are already registered or not.
  29.  
  30.         if(strpos("$username_or_email", "@"))
  31.         {
  32.             $email = $username_or_email;
  33.  
  34.             $query = "SELECT ids, usernames, passwords, emails, accounts_activations_statuses FROM users WHERE emails = ?";
  35.             $stmt = mysqli_stmt_init($conn);
  36.             $stmt = mysqli_prepare($conn, $query);            
  37.             mysqli_stmt_bind_param($stmt, 's', $email);
  38.             mysqli_stmt_execute($stmt);
  39.             //$result = mysqli_stmt_get_result($stmt); //Which line to use ? This line or the next ?
  40.             $result = mysqli_stmt_bind_result($stmt, $db_id, $db_username, $db_password, $db_email, $db_account_activation_status); // Which line to use ? This line or the one above ?
  41.         }
  42.         else
  43.         {
  44.             $username = $username_or_email;
  45.  
  46.             $query = "SELECT ids, usernames, passwords, emails, accounts_activations_statuses FROM users WHERE usernames = ?";
  47.             $stmt = mysqli_stmt_init($conn);
  48.             $stmt = mysqli_prepare($conn, $query);
  49.             mysqli_stmt_bind_param($stmt, 's', $username);
  50.             mysqli_stmt_execute($stmt);
  51.             $result = mysqli_stmt_bind_result($stmt, $db_id, $db_username, $db_password, $db_email, $db_account_activation_status); // Which line to use ? This line or the one above ?
  52.         }
  53.  
  54.         $row = mysqli_stmt_fetch($stmt);        
  55.         mysqli_stmt_close($stmt);
  56.  
  57.         if (!password_verify($password, $db_password))
  58.         {
  59.             echo "Incorrect User Credentials!';<br>";
  60.             exit();
  61.         }
  62.         else
  63.         {
  64.             $_SESSION["user"] = $db_username;            
  65.             header("location:home.php?user=$db_username");    
  66.         }
  67.     }
  68.  
  69.  
  70. ?>
  71.  
  72. <!DOCTYPE html>
  73. <html>
  74. <head>
  75. <title><?php $site_name?> Member Login Page</title>
  76.   <meta charset="utf-8">
  77. </head>
  78. <body>
  79. <form method="post" action="">
  80.     <h3><?= $site_name ?> Member Login Form</h3>
  81.     <fieldset>
  82.         <label for="login_name">Username/Email:</label>
  83.         <input type="text" name="login_username_or_email" id="login_name" value="">
  84.         <br>
  85.         <label for="login_pass">Password:</label>
  86.         <input type="password" name="login_password" id="login_pass" value="">
  87.     </fieldset>
  88.     <div class="submitsAndHiddens">
  89.         <label for="login_remember">Remember Login Details:</label>
  90.         <input type="checkbox" name="login_remember" />
  91.         <br>
  92.         <button type="submit">Login</button>
  93.         <br>
  94.         <a href="login_password_reset.php">Forgot your Password ? Reset it here!</a>
  95.         <br>
  96.         <a href="register.php">Register here!</a>
  97.     </div>
  98. </form>
  99.  
  100. </body>
  101. </html>
  102.  

registration.ph p (working)

Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. /*
  4. ERROR HANDLING
  5. */
  6. declare(strict_types=1);
  7. ini_set('display_errors', '1');
  8. ini_set('display_startup_errors', '1');
  9. error_reporting(E_ALL);
  10. mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
  11.  
  12. include 'config.php';
  13.  
  14. //Step 1: Before registering User account, check if User is already registered or not.
  15.  
  16. //Check if User is already logged-in or not.
  17. if (is_logged() === true) {
  18.     die("You are already logged-in! No need to register again!");
  19. }
  20.  
  21. if ($_SERVER['REQUEST_METHOD'] == "POST")
  22. {
  23. //Step 2: Check User Submitted Details.
  24.  
  25.     //Check if user made all the required inputs or not.
  26.     if (isset($_POST["username"]) && 
  27.        isset($_POST["password"]) &&
  28.        isset($_POST["password_confirmation"]) && 
  29.        isset($_POST["email"]) && 
  30.        isset($_POST["email_confirmation"]) && 
  31.        isset($_POST["first_name"]) && 
  32.        isset($_POST["surname"]) && 
  33.        isset($_POST["gender"])) {
  34.  
  35. //Step  3: Check User details for matches against database. If no matches then validate inputs and register User account.
  36.  
  37.         //Create variables based on user inputs.
  38.         $username     = trim($_POST["username"]);
  39.         $password     = $_POST["password"];
  40.         $password_confirmation = $_POST["password_confirmation"];
  41.         $email         = trim($_POST["email"]);
  42.         $email_confirmation = trim($_POST["email_confirmation"]);
  43.         $first_name    = trim($_POST["first_name"]);
  44.         $surname     = trim($_POST["surname"]);
  45.         $gender     = $_POST["gender"];    
  46.            $account_activation_code = sha1( (string) mt_rand(5, 30)); //Type Casted the INT to STRING on the 1st parameter of sha1 as it needs to be a STRING.
  47.         $account_activation_link = "http://www.".$site_domain."/".$social_network_name."/activate_account.php?email=".$_POST['email']."&account_activation_code=".$account_activation_code."";
  48.         $account_activation_status = 0; // 1 = active; 0 = not active.
  49.         $hashed_password = password_hash($password, PASSWORD_DEFAULT); //Encrypt the password.
  50.  
  51.         //Select Username and Email to check against Mysql DB if they are already registered or not.
  52.         $stmt = mysqli_prepare($conn, "SELECT usernames, emails FROM users WHERE usernames = ? OR emails = ?");
  53.         mysqli_stmt_bind_param($stmt, 'ss', $username, $email);
  54.         mysqli_stmt_execute($stmt);
  55.         $result = mysqli_stmt_get_result($stmt);        
  56.         $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
  57.  
  58.         // Check if inputted Username is already registered or not.
  59.         if ($row['usernames'] == $username) {
  60.             $_SESSION['error'] = "That username is already registered.";
  61.             exit();
  62.         // Check if inputted Username is between the required 8 to 30 characters long or not.
  63.         } elseif (strlen($username) < 8 || strlen($username) > 30) {
  64.             $_SESSION['error'] = "Username must be between 8 to 30 characters long!";
  65.             exit();
  66.         // Check if both inputted Emails match or not.
  67.         } elseif ($email != $email_confirmation) {
  68.             $_SESSION['error'] = "Emails don't match!";
  69.             exit();
  70.         // Check if inputed Email is valid or not.
  71.         } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  72.             $_SESSION['error'] = "Invalid email! Insert your real Email in order for us to email you your account activation details.";
  73.             exit();
  74.         // Check if inputted Email is already registered or not.
  75.         } elseif ($row['emails'] == $email) {
  76.             $_SESSION['error'] = "That email is already registered.";
  77.             exit();
  78.         // Check if both inputted Passwords match or not.
  79.         } elseif ($password != $password_confirmation) {
  80.             $_SESSION['error'] = "Passwords don't match.";
  81.             exit();
  82.         // Check if Password is between 8 to 30 characters long or not.
  83.         } elseif (strlen($password) < 8 || strlen($password) > 30) {
  84.             $_SESSION['error'] = "Password must be between 6 to 30 characters long!";
  85.             exit();
  86.         } 
  87.         else 
  88.         {
  89.             //Insert the user's inputs into Mysql database using php's sql injection prevention method "Prepared Statements".
  90.             $stmt = mysqli_prepare($conn, "INSERT INTO users(usernames, passwords, emails, first_names, surnames, genders, accounts_activations_codes, accounts_activations_statuses) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
  91.             mysqli_stmt_bind_param($stmt, 'sssssssi', $username, $hashed_password, $email, $first_name, $surname, $gender, $account_activation_code, $account_activation_status);
  92.             mysqli_stmt_execute($stmt);
  93.             echo "INSERTING";
  94.  
  95.             //Check if user's registration data was successfully submitted or not.
  96.             if (!$stmt)
  97.             {
  98.                 $_SESSION['error'] = "Sorry! Our system is currently experiencing a problem registering your account! You may try registering some other time.";
  99.                 exit();
  100.             }
  101.             else 
  102.             {
  103.                 //Email the account activation link for user to click it to confirm their email and activate their new account.
  104.                 $to = $email;
  105.                 $subject = "Your ".$site_name." account activation details!";
  106.                 $body  = nl2br("
  107.                 ===============================\r\n
  108.                 ".$site_name." \r\n
  109.                 ===============================\r\n
  110.                 From: ".$site_admin_email."\r\n
  111.                 To: ".$email."\r\n
  112.                 Subject: Yours ".$subject." \r\n
  113.                 Message: ".$first_name." ".$surname."\r\n You need to click on this following <a href=".$account_activation_link.">link</a> to activate your account. \r\n");
  114.                 $headers = "From: " . $site_admin_email . "\r\n";
  115.  
  116.                 if (!mail($to,$subject,$body,$headers)) 
  117.                 {
  118.                     $_SESSION['error'] = "Sorry! We have failed to email you your account activation details. Please contact the website administrator!";
  119.                     exit();
  120.                 }
  121.                 else
  122.                 {
  123.                     echo "<h3 style='text-align:center'>Thank you for your registration!<br /> Check your email for details on how to activate your account which you just registered.</h3>";
  124.                     exit();
  125.                 }
  126.             }
  127.         }
  128.     }
  129. }
  130.  
  131. ?>
  132.  
  133. <!DOCTYPE html>
  134. <html>
  135.     <head>
  136.         <title><?php $social_network_name ?> Signup Page</title>
  137.     </head>
  138. <body>
  139. <div class ="container">
  140.  
  141. <?php
  142. // Error Messages.
  143. if (isset($_SESSION['error']) && !empty($_SESSION['error'])) {
  144.     echo '<p style="color:red;">'.$_SESSION['error'].'</p>';
  145. }
  146. ?>
  147.  
  148. <?php
  149. //Session Messages.
  150. if (isset($_SESSION['message']) && !empty($_SESSION['message'])) {
  151.     echo '<p style="color:red;">'.$_SESSION['error'].'</p>';
  152. }
  153. ?>
  154.  
  155. <?php
  156. //Clear Registration Session.
  157. function clear_registration_session()
  158.     {
  159.         //Clear the User Form inputs, Session Messages and Session Errors so they can no longer be used.
  160.         unset($_SESSION['message']);
  161.         unset($_SESSION['error']);
  162.         unset($_POST);
  163.         exit();
  164.     }
  165. ?>
  166.  
  167. <form method="post" action="">
  168.     <center><h2>Signup Form</h2></center>
  169.     <div class="form-group">
  170.         <center><label>Username:</label>
  171.         <input type="text" placeholder="Enter a unique Username" name="username" required [A-Za-z0-9] value="<?php if(isset($_POST['username'])) { echo htmlentities($_POST['username']); }?>"></center>
  172.     </div>
  173.     <div class="form-group">
  174.         <center><label>Password:</label>
  175.         <input type="password" placeholder="Enter a new Password" name="password" required [A-Za-z0-9]></center>
  176.     </div>
  177.     <div class="form-group">
  178.         <center><label>Repeat Password:</label>
  179.         <input type="password" placeholder="Repeat a new Password" name="password_confirmation" required [A-Za-z0-9]></center>
  180.     </div>
  181.         <div class="form-group">
  182.         <center><label>Email:</label>
  183.         <input type="email" placeholder="Enter your Email" name="email" required [A-Za-z0-9] value="<?php if(isset($_POST['email'])) { echo htmlentities($_POST['email']); }?>"></center>
  184.     </div>
  185.     <div class="form-group">
  186.         <center><label>Repeat Email:</label>
  187.         <input type="email" placeholder="Repeat your Email" name="email_confirmation" required [A-Za-z0-9] value="<?php if(isset($_POST['email_confirmation'])) { echo htmlentities($_POST['email_confirmation']); }?>"></center>
  188.     </div>
  189.     <div class="form-group">
  190.         <center><label>First Name:</label>
  191.         <input type="text" placeholder="Enter your First Name" name="first_name" required [A-Za-z] value="<?php if(isset($_POST['first_name'])) { echo htmlentities($_POST['first_name']); }?>"></center>
  192.     </div>
  193.     <div class="form-group">
  194.         <center><label>Surname:</label>
  195.         <input type="text" placeholder="Enter your Surname" name="surname" required [A-Za-z] value="<?php if(isset($_POST['surname'])) { echo htmlentities($_POST['surname']); }?>"></center>
  196.     </div>
  197.     <div class="form-group">
  198.         <center><label>Gender:</label>
  199.         <input type="radio" name="gender" value="male" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Male<input type="radio" name="gender" value="female" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Female</center>
  200.     </div>
  201.     <center><button type="submit" class="btn btn-default" name="submit">Register!</button></center>
  202.     <center><font color="red" size="3"><b>Already have an account ?</b><br><a href="login.php">Login here!</a></font></center>
  203. </form>
  204. </div>
  205. </body>
  206. </html>
  207.  
account_activat ion.php (working)
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. /*
  4. ERROR HANDLING
  5. */
  6. declare(strict_types=1);
  7. ini_set('display_errors', '1');
  8. ini_set('display_startup_errors', '1');
  9. error_reporting(E_ALL);
  10. mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
  11.  
  12. include 'config.php';
  13.  
  14. if (!isset($_GET["email"], $_GET["account_activation_code"]) === true)
  15. {
  16.     $_SESSION['error'] = "Invalid Email Address! Invalid Account Activation Link! This email is not registered! Try registering an account if you do not already have one! <a href=\"register.php\">Register here!</a>";
  17.     exit();
  18. else 
  19. {    
  20.     $email = htmlspecialchars($_GET['email']);
  21.     $account_activation_code = htmlspecialchars($_GET['account_activation_code']);
  22.  
  23.     $stmt_one = mysqli_stmt_init($conn);    
  24.     if (mysqli_stmt_prepare($stmt_one, "SELECT usernames, accounts_activations FROM users WHERE emails = ? AND accounts_activations_codes = ?"))
  25.     {
  26.         mysqli_stmt_bind_param($stmt_one, 'si', $email,  $account_activation_code);
  27.         mysqli_stmt_execute($stmt_one);
  28.         mysqli_stmt_bind_result($stmt_one, $username, $account_activation_state);
  29.         mysqli_stmt_fetch($stmt_one);
  30.         mysqli_stmt_close($stmt_one);
  31.  
  32.         if ($account_activation_state != 0)
  33.         {    
  34.             echo "Since your account is already activated, why are you trying to activate it again ? Do not do that again and just login from <a href=\"login.php\">this webpage</a> next time! Make a note of that webpage, ok ?";
  35.             exit;
  36.         }
  37.         else
  38.         {
  39.             $account_activation_state = 1;
  40.  
  41.             $stmt_two = mysqli_stmt_init($conn);
  42.             if(mysqli_stmt_prepare($stmt_two, "UPDATE users SET accounts_activations = ? WHERE usernames = ?"))
  43.             {
  44.                 mysqli_stmt_bind_param($stmt_two, 'is', $account_activation_state, $username);
  45.                 mysqli_stmt_execute($stmt_two);    
  46.                 mysqli_stmt_fetch($stmt_two);
  47.                 mysqli_stmt_close($stmt_two);
  48.  
  49.                 echo "Account Activation State: $account_activation_state";?><br>
  50.                 <?php
  51.                 echo "Username: $username";            
  52.  
  53.                 echo "<h3 style='text-align:center'>Thank you for your confirming your email and activating your account.<br /> You may now try logging into your account.</h3>";
  54.                 $_SESSION["user"] = $username;
  55.             }
  56.             else
  57.             {
  58.                 echo 'Failure: Something is wrong. Unable to activate your account! Contact Site Admin.';
  59.                 echo 'Failure: Mysqli_stmt_prepare($stmt_two)';
  60.                 exit;
  61.             }
  62.         }    
  63.     }
  64.     else
  65.     {
  66.         echo 'Failure: This account activation link is invalid or has expired. Try <a href="register.php">registering</a> for an account now.';
  67.         echo 'Failure: Mysqli_stmt_prepare($stmt_one)';
  68.         exit;
  69.     }            
  70. }
  71.  
  72. ?>
  73.  
logout.php (working)

Expand|Select|Wrap|Line Numbers
  1. <?php
  2.        session_start();
  3.        session_destroy();
  4.        echo "You have successfully logged-out!";
  5. ?><br>
  6. <?php
  7.        echo "<a href='login.php'>Re-Login.</a>";
  8. ?><br>
  9.  
Oct 7 '17 #1
0 1695

Sign in to post your reply or Sign up for a free account.

Similar topics

10
12176
by: GreggTB | last post by:
I've got an page (LOGIN.ASPX) that receives the user's login information. During the page load, it checks the credentials against a database and, if validation is successful, creates an instance of an object that stores the user's basic profile data (username, user type, associated sales region, etc.). I've been taking this user info and...
3
2342
by: Dam6 | last post by:
Okay... Using vb .net within DW MX2004, connecting to an access database: Background: I have created a simple login.aspx page that is supposed to re-direct to default.aspx using FormsAuthentication.RedirectFromLoginPage. The data is correct from testing the dataset etc and the page also informs me that I have entered an incorrect user /...
1
2141
by: sharp2037 | last post by:
Hi Everyone, I am working on an ASP.net application and I have a homepage to which everyone visits of course and on that front page I have a user ID and password box and a login button. What I don't understand is some sites I visit don't use SSL on the login page. Instead you visit the homepage and there is no padlock. Then you type in...
7
2443
by: Alan Silver | last post by:
Hello, Sorry this is a bit wordy, but it's a pretty simple question... I have a web site, http://domain/ which is a public site, part of which (http://domain/a/) is protected by forms authentication. I would like to configure it so that anyone not logged in, trying to access the protected part will not be redirected to the login page,...
2
4218
by: Sasquatch | last post by:
I'm having trouble creating a simple login page using the asp:login control. I followed some instructions in a WROX book, "Beginning ASP.NET 2.0," and the instructions are very straight forward, but it won't work for me. Here's what I did. 1. Created a new folder named "testlogin" 2. Turned that folder into an application using the IIS...
2
2450
by: Sasquatch | last post by:
I'm still having trouble creating a simple login page using the asp:login control. I followed some instructions in a WROX book, "Beginning ASP.NET 2.0," and the instructions are very straight forward, but it won't work for me. I've got a little better troubleshooting information for everyone now. First, here's how I set this stuff up... ...
4
4067
tolkienarda
by: tolkienarda | last post by:
Hi all I work for a small webdesign company and we have remote hosting. i built a mysql database with phpmyadmin on the server. i then downloaded and modified a php login page. i am continuing to get the ---invalid username or password--- i am not getting the E_USER_ERROR so i don't know if there is a problem with the php, how i set up the...
2
2591
by: dgbergman | last post by:
I have created a php login page in my site for my company. The goal is to get people into members area. Below is a list of steps that I take to create my login page in Dreamweaver CS3, can some one verify that I have built the page correct and that is nothing wrong with the code. If there is something wrong with the code is it possible to explain...
9
7509
by: adweaver | last post by:
Hello All, I'm new to the world of php. I've just had a site designed for me by a company, and I'm now trying to manage and grow it, so it will suit my needs. The site was built in a folder called mysite.com/test. I coppied this folder a number of times, so I now have mysite.com/test2, mysite.com/test3 etc. Each folder acts as its own...
21
3839
by: tvnaidu | last post by:
This is the Java script I am using fo rlogin page, but cursor not pointing to login box, any idea how can I point cursor to login box when this page loaded?. here admin login take to control page and user login take to status page, if I give direct path without goto login, both pages display, can I add a check if user didn't login, then redirect...
0
7584
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7888
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8108
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7644
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7951
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6260
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3643
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2083
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.