How to create php login script with remember me

By Axl on

Login is the one of the security in our website, it is a procedure to gain access in our web application gain access such as admin page, control page or profile page. Login almost requires username and password websites, desktop application and mobile application.

Most popular website like an ecommerce or bank website, there login system has advance features they implemented, for example at least one digit in password, must have special character or not allowed natural language word. In this tutorial we make simple and understandable for our friend newbies web developer.

we create a simple php login script with remember me, this php login has a cookie based remember me features, so if the user checked the remember me check box and they logged in, then if the users close the browser the session will not completely deleted because the checkbox value has stored a cookie, if they came back to the browser it will redirect to home page template.

Demo

Step 1: create database and Insert Sample User

First thing do to is to create database, so go to your phpmyadmin and create database name for this example ‘axlmulat_demo’

CREATE TABLE `user_demo` (
  `id` int(10) UNSIGNED NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(100) NOT NULL
);
ALTER TABLE `user_demo`ADD PRIMARY KEY (`id`);
ALTER TABLE `user_demo` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;

INSERT INTO `user_demo` (`username` , `password`) VALUES ('axl', SHA1( 'strongpass125' ))

Step 2: php database connection

includes/connection.php

<?php
	$db = mysqli_connect('localhost', 'root', '', 'axlmulat_demo');
	if(!$db) { echo mysqli_connect_error(); }
?>

To connect from the mysql database we have assigning the database credentials: MySQL host, user, password and database name the ‘axlmulat_demo’ for this example.

Step 3: Login Page

index.php

<?php session_start(); // session, put every page ?>
<?php
if( isset($_SESSION['username']) || isset($_COOKIE['username'])) { // if session or cookie is stored
	header("Location: home.php"); // redirect to home, no need to logged in
	exit();
}
?>
<?php require_once("includes/connection.php"); // database connection ?>
<?php
	if(isset($_POST['login'])) {

		$username		 	= trim($_POST['username']);
		$password		 	= trim($_POST['password']);
		$hashed_password 	= sha1($password);
		$remember 			= @$_POST['remember'];

		$query = mysqli_query($db, "SELECT `id`, `username` FROM `user_demo` WHERE `username` = '$username' AND `password` = '$hashed_password'");
		if(!$query) {
			die("Database query failed: " . mysqli_error($db));
		}
		if(mysqli_num_rows($query) == 1) { // if found the user in database, store session
			$found_user = mysqli_fetch_assoc($query);
			//$_SESSION['user_id'] 	= $found_user['id'];
			//$_SESSION['username'] = $found_user['username'];

			if($remember == "yes") { // if checked the 'Remember me' checkbox, store the user id in cookie

						  // name,    value,                    ,expire date,      path
				setcookie('username', $found_user['username'] , time()+(60*60*24*7), ""); // seconds,  minutes,  day, week
			} else {
				$_SESSION['username'] 	= $found_user['username'];
				}

			header("Location: home.php");
			exit();

		} else { // else user/password incorrect

			header("Location: index.php?log=error");
			exit();

		  }

	}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex,nofollow"/>
<title>How to create php login script with mysql</title>
<link href="css/style.css" rel="stylesheet" type="text/css" media="all" />
</head>

<body>
	<div id="wrapper">
    	<h2 class="logo">Login</h2>

    	<div id="login-box">

		<?php if(isset($_GET['log']) == 'error') { ?>
       	 	<p class="msg"> Username/Combination Incorrect.</p>
        <?php } elseif (isset($_GET['logout']) == '1') { ?>
     		<p class="msg">You Are Logout.</p>
		<?php } ?>

    	<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
        	<table>
            	<tr>
                	<td>Username: </td>
                    <td> <input name="username" type="text" value=""> </td>

                </tr>
                <tr>
                	<td>Password: </td>
                    <td><input name="password" type="password" value=""></td>

                </tr>
                <tr>
                	<td>&nbsp;</td>
                    <td><input name="login" type="submit" value="Log in"><input name="remember" type="checkbox" value="yes"> Remember me.</td>

                </tr>
                </table>

        </form>
        </div>  <!--login-box end-->
        <br />
        <p><strong>Sample User:</strong> axl <strong>Password:</strong> strongpass125</p>

       </div> <!--wrapper end-->
</body>
</html>

Now in this page our main process, as you see in this page I put all together the session, redirect and mysql insert query. You may wonder I did not put these in the functions or object oriented style, because for easy to understand for web dev beginners, it’s up to if you convert these into functions.

css/style.css

body  {
	font-family: verdana,helvetica,arial,sans-serif;
	font-size: 12px;
	background:#cccccc;
}
div#wrapper {
    background: none repeat scroll 0 0 #FFFFFF;
    padding: 30px;
}
.msg { color: #F00; }
.logo { color:#3399FF; }

Our simple style

Step 4: Home Page

home.php

<?php session_start(); // session, put every page ?>
<?php
if( isset($_SESSION['username']) || isset($_COOKIE['username']) ) {  // if session or cookie is stored, put this in every private page
	//
} else { // else not stored
	header("Location: index.php"); // redirect to home login page
	exit();
	}
?>
<?php require_once("includes/connection.php"); // database connection ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Home</title>
<link href="css/style.css" rel="stylesheet" type="text/css" media="all" />
</head>

<body>
<div id="wrapper">
    <h2 class="logo">Home</h2>

   <?php
	if( isset($_SESSION['username'])) {
		$username = $_SESSION['username']. ' (You logged in via session)';
	} elseif($_COOKIE['username']) {
		$username = $_COOKIE['username'] . ' (You logged in via cookie)';
		}
	?>

    Welcome, <b><?php echo $username; ?></b>

    <br /><br />
    <a href="#" rel="noopener">Home</a> |
    <a href="#" rel="noopener">About Us</a> |
    <a href="logout.php" onclick="return confirm('Are you sure you want to logout?');">Logout</a>
    </div> <!--wrapper end-->

</body>
</html>

Put this in every private page, if the user not login and access the page directly, it will redirect to the login page template.

Step 5: Log out Process

logout.php

<?php
session_start(); //start session

//destroy session
session_destroy();

//unset cookies
setcookie("username", "", time()-3600, ""); // name, cookie value set to blank, time set to pass, path set to cookie - in this case blank becuase in redirect to index.php

header ("Location: index.php?logout=1");
exit();
?>

Done

We’re done, Congratulations. Finally were created our first php login script, I create this guys in step by step and coded with explanation, so beginner developer can easy to understand and you can download the work files link at the top.

Thank you for reading my tutorial. Please recommend and share