PHP (Core & Framework)

How to implement auto login in php using cookies ?


We can create auto login using cookies in php , this feature is required in case you want  to create web view of your website , as mobile user don’t want to login every time they open your android app (web view of your web site. You can use the code below tom implement the auto-login on your php based website

PHP code for Auto Login :



include(“connect.php”); // your mysql connect code

// code to read user name and password in cookies on client machine
if(isset($_COOKIE[“username”])) $email= $_COOKIE[“username”]; else $email=””;
if(isset($_COOKIE[“password”])) $pwd=$_COOKIE[“password”]; else $pwd=””;

// if cookies are set for login details then we compare the login details with database //and redirect the user directly to page after login so user is not required to input //login details and then  click on login button

if ($email!=””)
$sql= “select * from members where username='”.$email.”‘ and user_pwd='”.$pwd.”‘”;
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
if($count > 0 && $row[‘auto_login’]==1)

$_SESSION[‘uname’] = $email;
setcookie (“username”,$email,time()+ 3600);
setcookie (“password”,$pwd,time()+ 3600);
<!DOCTYPE html>
<html lang=”en”>
<title>My Expense-Login</title>
<meta charset=”utf-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<link rel=”stylesheet” href=””>
<script src=””></script>
<script src=””></script>
<script src=””></script>
<?php include(“top-menu-login.php”); ?>
<div class=”container”>
<div class=”row”>

<div class=”col-md-3″></div>
<div class=”col-md-6″>
<h2 class=”text-center”>User Login</h2>

<div id=”message”></div>
<div class=”form-group”>
<label for=”email”>Email address:</label>

<!– here we check if cookies is set then auto fill the login details –>
<input type=”email” class=”form-control” id=”email” name=”email” value=”<?php if(isset($_COOKIE[“username”])) { echo $_COOKIE[“username”]; } ?>”>
<div class=”form-group”>
<label for=”pwd”>Password:</label>
<input type=”password” class=”form-control” id=”pwd” name=”pwd” value=”<?php if(isset($_COOKIE[“password”])) { echo $_COOKIE[“password”]; } ?>” >
<div class=”form-group ml-4″>
<label class=”form-check-label”>
<input class=”form-check-input” type=”checkbox” name=”remember” id=”remember” <?php if(isset($_COOKIE[“username”])) { echo “checked”; } ?>> Auto Login
<label class=”form-signup”>
<a href=”forgot-pass.php” class=”btn btn-light”> Forgot Passsword </a>
<button type=”button” class=”btn btn-primary” id=”btn-submit”>Submit</button>
<button type=”button” class=”btn btn-success” id=”btn-register”>Register</button>

<div class=”col-md-3″><br>


Comment here