Webmaster Sun Login
Not a member yet? Sign up

How To Add Remember Me Feature With Cookies ?

  • HOME
  • FORUMS
  • BLOGS
  • MARKETPLACE
  • ADVERTISING
  • SPECIAL OFFERS
  • WEB HOSTING
  • QUICK MENU
  • REGISTER HERE - Join us for FREE
Results 1 to 4 of 4
    Stick this thread
  1. #1
    Join Date
    Jun 2017
    Posts
    33
    Thumbs Up/Down
    Received: 0/0
    Given: 9/0
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Question How To Add Remember Me Feature With Cookies ?

    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.php, logout.php and account_acivation.php finished. Those last 3 files are working fine. Working on the home.php now.

    login.php
    Code:
    <?php
     
    /*
    ERROR HANDLING
    */
    declare(strict_types=1);
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
     
    include 'config.php';
     
    // check if user is already logged in
    if (is_logged() === true) 
    {
    	//Redirect user to homepage page after 5 seconds.
    	header("refresh:2;url=home.php");
    	exit; //
    }
    
    
    if (isset($_POST["login_username_or_email"]) && isset($_POST["login_password"]))
    	{
    		$username_or_email = trim($_POST["login_username_or_email"]);
    		$password = $_POST["login_password"];		
             
    		//Select Username or Email to check against Mysql DB if they are already registered or not.
    				
            if(strpos("$username_or_email", "@"))
    		{
    			$email = $username_or_email;
    						
    			$query = "SELECT ids, usernames, passwords, emails, accounts_activations_statuses FROM users WHERE emails = ?";
    			$stmt = mysqli_stmt_init($conn);
    			$stmt = mysqli_prepare($conn, $query);			
    			mysqli_stmt_bind_param($stmt, 's', $email);
    			mysqli_stmt_execute($stmt);
    		    //$result = mysqli_stmt_get_result($stmt); //Which line to use ? This line or the next ?
    			$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 ?
    		}
    		else
    		{
    			$username = $username_or_email;
    						
    			$query = "SELECT ids, usernames, passwords, emails, accounts_activations_statuses FROM users WHERE usernames = ?";
    			$stmt = mysqli_stmt_init($conn);
    			$stmt = mysqli_prepare($conn, $query);
    			mysqli_stmt_bind_param($stmt, 's', $username);
    			mysqli_stmt_execute($stmt);
    			$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 ?
    		}
          	
    		$row = mysqli_stmt_fetch($stmt);		
    		mysqli_stmt_close($stmt);
    		
    		if (!password_verify($password, $db_password))
    		{
    			echo "Incorrect User Credentials!';<br>";
    			exit();
    		}
    		else
    		{
    			$_SESSION["user"] = $db_username;			
    			header("location:home.php?user=$db_username");	
    		}
    	}
    
    	
    ?>
    
    <!DOCTYPE html>
    <html>
    <head>
    <title><?php $site_name?> Member Login Page</title>
      <meta charset="utf-8">
    </head>
    <body>
    <form method="post" action="">
    	<h3><?= $site_name ?> Member Login Form</h3>
    	<fieldset>
    		<label for="login_name">Username/Email:</label>
    		<input type="text" name="login_username_or_email" id="login_name" value="">
    		<br>
    		<label for="login_pass">Password:</label>
    		<input type="password" name="login_password" id="login_pass" value="">
    	</fieldset>
    	<div class="submitsAndHiddens">
    		<label for="login_remember">Remember Login Details:</label>
    		<input type="checkbox" name="login_remember" />
    		<br>
    		<button type="submit">Login</button>
    		<br>
    		<a href="login_password_reset.php">Forgot your Password ? Reset it here!</a>
    		<br>
    		<a href="register.php">Register here!</a>
    	</div>
    </form>
    
    </body>
    </html>

    registration.php (working)

    Code:
    <?php
    
    /*
    ERROR HANDLING
    */
    declare(strict_types=1);
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    
    include 'config.php';
    
    //Step 1: Before registering User account, check if User is already registered or not.
    
    //Check if User is already logged-in or not.
    if (is_logged() === true) {
    	die("You are already logged-in! No need to register again!");
    }
    
    if ($_SERVER['REQUEST_METHOD'] == "POST")
    {
    //Step 2: Check User Submitted Details.
    	
    	//Check if user made all the required inputs or not.
    	if (isset($_POST["username"]) && 
    	   isset($_POST["password"]) &&
    	   isset($_POST["password_confirmation"]) && 
    	   isset($_POST["email"]) && 
    	   isset($_POST["email_confirmation"]) && 
    	   isset($_POST["first_name"]) && 
    	   isset($_POST["surname"]) && 
    	   isset($_POST["gender"])) {
    		   
    //Step  3: Check User details for matches against database. If no matches then validate inputs and register User account.
    		   
    		//Create variables based on user inputs.
    		$username 	= trim($_POST["username"]);
    		$password 	= $_POST["password"];
    		$password_confirmation = $_POST["password_confirmation"];
    		$email 		= trim($_POST["email"]);
            $email_confirmation = trim($_POST["email_confirmation"]);
            $first_name	= trim($_POST["first_name"]);
            $surname 	= trim($_POST["surname"]);
    		$gender 	= $_POST["gender"];	
    	   	$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.
    		$account_activation_link = "http://www.".$site_domain."/".$social_network_name."/activate_account.php?email=".$_POST['email']."&account_activation_code=".$account_activation_code."";
    		$account_activation_status = 0; // 1 = active; 0 = not active.
            $hashed_password = password_hash($password, PASSWORD_DEFAULT); //Encrypt the password.
            
    		//Select Username and Email to check against Mysql DB if they are already registered or not.
    		$stmt = mysqli_prepare($conn, "SELECT usernames, emails FROM users WHERE usernames = ? OR emails = ?");
    		mysqli_stmt_bind_param($stmt, 'ss', $username, $email);
    		mysqli_stmt_execute($stmt);
    		$result = mysqli_stmt_get_result($stmt);		
    		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
            
    		// Check if inputted Username is already registered or not.
    		if ($row['usernames'] == $username) {
    			$_SESSION['error'] = "That username is already registered.";
    			exit();
    		// Check if inputted Username is between the required 8 to 30 characters long or not.
    		} elseif (strlen($username) < 8 || strlen($username) > 30) {
    			$_SESSION['error'] = "Username must be between 8 to 30 characters long!";
    			exit();
    		// Check if both inputted Emails match or not.
    		} elseif ($email != $email_confirmation) {
    			$_SESSION['error'] = "Emails don't match!";
    			exit();
    		// Check if inputed Email is valid or not.
    		} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    			$_SESSION['error'] = "Invalid email! Insert your real Email in order for us to email you your account activation details.";
    			exit();
    		// Check if inputted Email is already registered or not.
    		} elseif ($row['emails'] == $email) {
    			$_SESSION['error'] = "That email is already registered.";
    			exit();
    		// Check if both inputted Passwords match or not.
    		} elseif ($password != $password_confirmation) {
    			$_SESSION['error'] = "Passwords don't match.";
    			exit();
    		// Check if Password is between 8 to 30 characters long or not.
    		} elseif (strlen($password) < 8 || strlen($password) > 30) {
    			$_SESSION['error'] = "Password must be between 6 to 30 characters long!";
    			exit();
    		} 
    		else 
    		{
    			//Insert the user's inputs into Mysql database using php's sql injection prevention method "Prepared Statements".
    			$stmt = mysqli_prepare($conn, "INSERT INTO users(usernames, passwords, emails, first_names, surnames, genders, accounts_activations_codes, accounts_activations_statuses) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    			mysqli_stmt_bind_param($stmt, 'sssssssi', $username, $hashed_password, $email, $first_name, $surname, $gender, $account_activation_code, $account_activation_status);
    			mysqli_stmt_execute($stmt);
    			echo "INSERTING";
    
    			//Check if user's registration data was successfully submitted or not.
    			if (!$stmt)
    			{
    				$_SESSION['error'] = "Sorry! Our system is currently experiencing a problem registering your account! You may try registering some other time.";
    				exit();
    			}
    			else 
    			{
    				//Email the account activation link for user to click it to confirm their email and activate their new account.
    				$to = $email;
    				$subject = "Your ".$site_name." account activation details!";
    				$body  = nl2br("
    				===============================\r\n
    				".$site_name." \r\n
    				===============================\r\n
    				From: ".$site_admin_email."\r\n
    				To: ".$email."\r\n
    				Subject: Yours ".$subject." \r\n
    				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");
    				$headers = "From: " . $site_admin_email . "\r\n";
    			
    			    if (!mail($to,$subject,$body,$headers)) 
    				{
    					$_SESSION['error'] = "Sorry! We have failed to email you your account activation details. Please contact the website administrator!";
    					exit();
    				}
    				else
    				{
    					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>";
    					exit();
    				}
    			}
    	    }
    	}
    }
    
    ?>
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title><?php $social_network_name ?> Signup Page</title>
    	</head>
    <body>
    <div class ="container">
    
    <?php
    // Error Messages.
    if (isset($_SESSION['error']) && !empty($_SESSION['error'])) {
    	echo '<p style="color:red;">'.$_SESSION['error'].'</p>';
    }
    ?>
    
    <?php
    //Session Messages.
    if (isset($_SESSION['message']) && !empty($_SESSION['message'])) {
    	echo '<p style="color:red;">'.$_SESSION['error'].'</p>';
    }
    ?>
    
    <?php
    //Clear Registration Session.
    function clear_registration_session()
    	{
    		//Clear the User Form inputs, Session Messages and Session Errors so they can no longer be used.
    		unset($_SESSION['message']);
    		unset($_SESSION['error']);
    		unset($_POST);
    		exit();
    	}
    ?>
    
    <form method="post" action="">
    	<center><h2>Signup Form</h2></center>
    	<div class="form-group">
    		<center><label>Username:</label>
    		<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>
    	</div>
    	<div class="form-group">
    		<center><label>Password:</label>
    		<input type="password" placeholder="Enter a new Password" name="password" required [A-Za-z0-9]></center>
    	</div>
    	<div class="form-group">
    		<center><label>Repeat Password:</label>
    		<input type="password" placeholder="Repeat a new Password" name="password_confirmation" required [A-Za-z0-9]></center>
    	</div>
    		<div class="form-group">
    		<center><label>Email:</label>
    		<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>
    	</div>
    	<div class="form-group">
    		<center><label>Repeat Email:</label>
    		<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>
    	</div>
    	<div class="form-group">
    		<center><label>First Name:</label>
    		<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>
    	</div>
    	<div class="form-group">
    		<center><label>Surname:</label>
    		<input type="text" placeholder="Enter your Surname" name="surname" required [A-Za-z] value="<?php if(isset($_POST['surname'])) { echo htmlentities($_POST['surname']); }?>"></center>
    	</div>
    	<div class="form-group">
    		<center><label>Gender:</label>
    		<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>
    	</div>
    	<center><button type="submit" class="btn btn-default" name="submit">Register!</button></center>
    	<center><font color="red" size="3"><b>Already have an account ?</b><br><a href="login.php">Login here!</a></font></center>
    </form>
    </div>
    </body>
    </html>
    account_activation.php (working)
    Code:
    <?php
    
    /*
    ERROR HANDLING
    */
    declare(strict_types=1);
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    
    include 'config.php';
    
    if (!isset($_GET["email"], $_GET["account_activation_code"]) === true)
    {
        $_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>";
        exit();
    } 
    else 
    {	
    	$email = htmlspecialchars($_GET['email']);
    	$account_activation_code = htmlspecialchars($_GET['account_activation_code']);
    
    	$stmt_one = mysqli_stmt_init($conn);	
    	if (mysqli_stmt_prepare($stmt_one, "SELECT usernames, accounts_activations FROM users WHERE emails = ? AND accounts_activations_codes = ?"))
    	{
    		mysqli_stmt_bind_param($stmt_one, 'si', $email,  $account_activation_code);
    		mysqli_stmt_execute($stmt_one);
    		mysqli_stmt_bind_result($stmt_one, $username, $account_activation_state);
    		mysqli_stmt_fetch($stmt_one);
    		mysqli_stmt_close($stmt_one);
        	
    		if ($account_activation_state != 0)
    		{	
    			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 ?";
    			exit;
    		}
    		else
    		{
    			$account_activation_state = 1;
    				
    			$stmt_two = mysqli_stmt_init($conn);
    			if(mysqli_stmt_prepare($stmt_two, "UPDATE users SET accounts_activations = ? WHERE usernames = ?"))
    			{
    				mysqli_stmt_bind_param($stmt_two, 'is', $account_activation_state, $username);
    				mysqli_stmt_execute($stmt_two);	
    				mysqli_stmt_fetch($stmt_two);
    				mysqli_stmt_close($stmt_two);
    			
    				echo "Account Activation State: $account_activation_state";?><br>
    				<?php
    				echo "Username: $username";			
    		
    				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>";
    				$_SESSION["user"] = $username;
    			}
    			else
    			{
    				echo 'Failure: Something is wrong. Unable to activate your account! Contact Site Admin.';
    				echo 'Failure: Mysqli_stmt_prepare($stmt_two)';
    				exit;
    			}
    		}	
    	}
    	else
    	{
    		echo 'Failure: This account activation link is invalid or has expired. Try <a href="register.php">registering</a> for an account now.';
    		echo 'Failure: Mysqli_stmt_prepare($stmt_one)';
    		exit;
    	}			
    }
    
    ?>
    logout.php (working)

    Code:
    <?php
           session_start();
           session_destroy();
           echo "You have successfully logged-out!";
    ?><br>
    <?php
           echo "<a href='login.php'>Re-Login.</a>";
    ?><br>

  2. #2
    Join Date
    Apr 2016
    Location
    United States
    Posts
    462
    Thumbs Up/Down
    Received: 304/0
    Given: 33/0
    Thanks
    28
    Thanked 152 Times in 106 Posts
    I have some great example videos on my site, you should check them out.

    To ask someone to walk through all that code is quite an undertaking and would require a couple of hours to go through and clean up.
    Mike
    Learn Web Development - OnLine Video Training OnTargetHTML5
    Have Questions On Training or Web Development: Contact Mike

  3. #3
    Join Date
    Jun 2017
    Posts
    33
    Thumbs Up/Down
    Received: 0/0
    Given: 9/0
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Mike001 View Post
    I have some great example videos on my site, you should check them out.

    To ask someone to walk through all that code is quite an undertaking and would require a couple of hours to go through and clean up.
    I'm sure you have coded a persistent cookie on your login page. You can easily show everybody how to code it by working on my code. Where is your link ?

  4. #4
    Join Date
    Apr 2016
    Location
    United States
    Posts
    462
    Thumbs Up/Down
    Received: 304/0
    Given: 33/0
    Thanks
    28
    Thanked 152 Times in 106 Posts
    I do not use cookies on my home page or any page of my site, I have used them for customer sites at their request but I try to convince them that Sessions are a better fit for them and there customers.

    Now what you have asked would not work in a Session as the sessions are destroyed as soon as the user exits the site.

    I am quite surprised that you would make an assumption that I could easily go through your code and make changes easily. Obviously to you my time is worth nothing. Just because you have a block of code listed as working does not in anyway mean that the code is working for what you are trying to do.
    Mike
    Learn Web Development - OnLine Video Training OnTargetHTML5
    Have Questions On Training or Web Development: Contact Mike

Newer Threads

  1. questionmark
    Hello Everyone!!
    By questionmark in forum New Member Introductions
    ulterios
    Replies: 3 | Views: 92
    Last post by ulterios, 10-08-2017, 11:08 PM
  2. mildredtabitha
    mildredtabitha
    Replies: 3 | Views: 87
    Last post by mildredtabitha, 10-08-2017, 02:40 PM
  3. kammy
    vishwa
    Replies: 3 | Views: 85
    Last post by vishwa, 10-09-2017, 03:38 AM
  4. mildredtabitha
    mildredtabitha
    Replies: 0 | Views: 41
    Last post by mildredtabitha, 10-07-2017, 03:18 PM
  5. akshaychouhan785
    Bluehost basic hosting package?
    By akshaychouhan785 in forum Web Hosting
    EzzyTech-Sakib
    Replies: 4 | Views: 144
    Last post by EzzyTech-Sakib, 10-10-2017, 01:19 PM

Older Threads

  1. TheAuthor
    TheAuthor
    Replies: 0 | Views: 234
    Last post by TheAuthor, 10-06-2017, 07:49 PM
  2. JenS
    UnrivaledReview
    Replies: 3 | Views: 76
    Last post by UnrivaledReview, Today, 11:22 AM
  3. Saira shergill
    sidrawat
    Replies: 1 | Views: 64
    Last post by sidrawat, 10-05-2017, 09:48 AM
  4. sunny_pro
    sunny_pro
    Replies: 6 | Views: 113
    Last post by sunny_pro, 10-06-2017, 11:04 PM
  5. technbyte
    premiumproxies
    Replies: 3 | Views: 135
    Last post by premiumproxies, 10-10-2017, 05:13 AM

Latest Threads

  1. UnrivaledReview
    Hoping I Can Help
    By UnrivaledReview in forum New Member Introductions
    UnrivaledReview
    Replies: 0 | Views: 6
    Last post by UnrivaledReview, Today, 10:37 AM
  2. Diana Bitter
    Diana Bitter
    Replies: 0 | Views: 65
    Last post by Diana Bitter, Today, 10:00 AM
  3. Hostigger
    Hostigger
    Replies: 2 | Views: 56
    Last post by Hostigger, Today, 07:01 AM
  4. eeecentric
    Rob Whisonant
    Replies: 1 | Views: 50
    Last post by Rob Whisonant, Today, 06:06 AM

Similar Threads

  1. sunny_pro
    sunny_pro
    Replies: 2 | Views: 77
    Last post by sunny_pro, 09-29-2017, 01:10 PM
  2. Edward
    Delimiter
    Replies: 4 | Views: 927
    Last post by Delimiter, 05-11-2016, 08:39 PM
  3. Maxwell
    jamesalan
    Replies: 2 | Views: 1207
    Last post by jamesalan, 04-10-2015, 01:14 PM
  4. Liliana
    buzybee-kevin
    Replies: 4 | Views: 2990
    Last post by buzybee-kevin, 10-27-2014, 12:28 AM
  5. vaneetagoswami
    vaneetagoswami
    Replies: 10 | Views: 2773
    Last post by vaneetagoswami, 06-09-2014, 04:59 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  

Internet Marketing Forum

Webmaster Sun is a forum where you’ll find in-depth discussions and resources to help you succeed on the web whether you are new or experienced. You’ll find it all here. With topics ranging from internet marketing, search engine optimization, social networking, make money online, web hosting, affiliate marketing as well as hands-on technical support for web design, programming and more. We are a growing community of like-minded people that is keen to help and support each other with ambitions and online endeavors. Learn and grow, make friends and contacts for life.

Come Hang Out With Us

    Facebook Twitter Webmaster Forum Google+

    Webmaster Sun Logo
Copyright ©2012 - 2017, WebmasterSun.com. All rights reserved. Internet marketing forum for internet marketers, webmasters, web hosting providers, designers and affiliate marketers.

Welcome to Webmaster Sun

The World's Number 1 Webmaster Community, SEO and Marketplace

Log in!

Continue with Facebook
Continue With Email. By signing up you indicate that you have read and agree to the Terms of Service and Privacy Policy.

Sign in Manually

Need an account? Sign up now!