Login Script with Remember Me in PHP
On login page remember me feature is used to preserve the login name and password entered by the user. And it can be populated in the login form at the time of login. It minimizes the user effort by preventing to enter login details again and again.
Login Form
First we have to design your login form as shown in above image, this form contain remember me check box. If it is set then the login details entered by the user will be preserved for future login attempts.
<table cellpadding=”10″>
<tr>
<td><label for=”login”>Username</label></td>
<td><input name=”user_name” type=”text” value=”<?php if(isset($_COOKIE[“user_name”])) { echo $_COOKIE[“user_name”]; } ?>”></td>
</tr>
<tr>
<td><label for=”password”>Password</label></td>
<td><input name=”user_password” type=”password” value=”<?php if(isset($_COOKIE[“user_password”])) { echo $_COOKIE[“user_password”]; } ?>”></td>
</tr>
<tr>
<td><input type=”checkbox” name=”remember” id=”remember” <?php if(isset($_COOKIE[“user_name”])) { ?> checked <?php } ?> /></td>
<td><label for=”remember-me”>Remember me</label></td>
</tr>
<tr>
<td><input type=”submit” name=”login” value=”Login”></span></td>
</tr>
</table>
</form>
PHP Cookie to Remember Login
Next we will code to validate the login details entered by the user while submitting the form and it checks whether remember me is checked or not. If checked, it stores the user login and password in PHP $_COOKIE array. If these array variables are not empty then will be populated in the login form fields.
session_start();
if(!empty($_REQUEST[“login”])) {
$conn = mysqli_connect(“my_host”, “user”, “password”, “my_database”);
$sql = “Select * from user where username = ‘” . $_REQUEST[“user_name”] . “‘ and password = ‘” . md5($_REQUEST[“user_password”]) . “‘”;
$result = mysqli_query($conn,$sql);
$user = mysqli_fetch_array($result);
if($user) {
$_SESSION[“member_id”] = $user[“id”];
if(!empty($_REQUEST[“remember”])) {
setcookie (“user_name”,$_REQUEST[“user_name”],time()+ (10 * 365 * 24 * 60 * 60));
setcookie (“user_password”,$_REQUEST[“user_password”],time()+ (10 * 365 * 24 * 60 * 60));
} else {
if(isset($_COOKIE[“user_name”])) {
setcookie (“user_name”,””);
}
if(isset($_COOKIE[“user_password”])) {
setcookie (“user_password”,””);
}
}
} else {
$message = “Invalid Login”;
}
}
?>