All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

PHP Login Page With Session And Cookies Example

Last Updated : Jul 1, 2023

PHP Login Page With Session And Cookies Example

In this tutorial we will show you the solution of PHP login page with session and cookies example, here we created five php files for navigate to another page when user login information is correct.

In index page we collecting user name, password for user verification then we storing user information’s on session and cookie variables.

We checking database information with login information if they correct then we can navigate to home page and when we needs to logout user’s stored information will also removed.

Step By Step Guide On PHP Login Page With Session And Cookies Example :-

Here Here we start our session then we executed database connection. In html block we defined login form with input fields for collecting user name, password and another one is submit button then we sets cookie name, password as user entering inputs.

After filled login form we checks whether valid user or not in login page if they valid we sets cookie information for particular amount of time.

Then we navigate to success page otherwise it throws error message and returns to login page.

In success page we retrieving that user name by session id and displaying user name with success message.

If user need to logout there we provided logout option when they click on that link then stored session and cookie information about that user will removed and returns to index page.

<?php
 session_start();
 include('dbcon.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Login with Session&Cookie </title>
</head>
<body>
 <h2>Login Form</h2>
 <form method="POST" action="login.php">
 <label>Username:</label><input type="text" value="<?php if (isset($_COOKIE["user"])){echo $_COOKIE["user"];}?>" name="username">
 <label>Password:</label><input type="password" value="<?php if (isset($_COOKIE["pass"])){echo $_COOKIE["pass"];}?>" name="password"><br><br>
 <input type="checkbox" name="remember"<?php if (isset($_COOKIE["user"]) && isset($_COOKIE["pass"])){ echo "checked";}?>> Remember me <br><br>
 <input type="submit" value="Login" name="login">
 </form>
 <span>
 <?php
  if (isset($_SESSION['message'])){
   echo $_SESSION['message'];
  }
  unset($_SESSION['message']);
 ?>
</span>
</body>
</html>

Dbcon.php

<?php
    $hName='localhost';
    $uName='root';
    $password='';
    $dbName = "dbase";
    $dbCon = mysqli_connect($hName,$uName,$password,"$dbName");
     if(!$dbCon){
          die('Could not Connect MySql Server:' .mysql_error());
      }
?>

Login.php

<?php
 if(isset($_POST['login'])){
  session_start();
  include('dbcon.php');
  $username=$_POST['username'];
  $password=$_POST['password'];
  $query=mysqli_query($dbCon,"select * from `info` where Name='$username'&& Password='$password'");
  if (mysqli_num_rows($query) == 0){
   $_SESSION['message']="Login Failed. User not Found!";
   header('location:loginSSCK.php');
  }
  else{
   $row=mysqli_fetch_array($query);
   if (isset($_POST['remember'])){
    setcookie("user", $row['Name'], time() + (86400 * 30));
    setcookie("pass", $row['Password'], time() + (86400 * 30));
   }
   $_SESSION['id']=$row['ID'];
   header('location:success.php');
  }
 }
 else{
  header('location:loginSSCK.php');
  $_SESSION['message']="Please Login!";
 }
?>

Home.php

<?php
 session_start();
 if (!isset($_SESSION['id']) ||(trim ($_SESSION['id']) == '')) {
  header('loginSSCK.php');
  exit();
 }
 include('dbcon.php');
 $query=mysqli_query($dbCon,"select * from info where ID='".$_SESSION['id']."'");
 $row=mysqli_fetch_assoc($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Home page</title>
</head>
<body>
 <h2>Login Success</h2>
 <?php echo $row['Name']; ?>
 <br>
 <a href="logout.php">Logout</a>
</body>
</html>

Logout.php

<?php
 session_start();
 session_destroy();
 if (isset($_COOKIE["user"]) AND isset($_COOKIE["pass"])){
  setcookie("user", '', time() - (3600));
  setcookie("pass", '', time() - (3600));
 }
 header('location:loginSSCK.php');
?>
  1. A php script can be placed anywhere in the document. A php script starts with <?php and end with ?>.
  2. The default file extension for php files is “.php” and php statements end with ‘;’ semicolon.
  3. In html block we starts session and we called once dbcon.php file for executes database ‘dbase’ connection.
  4. The mysqli_connect() method will executes database connection for that we need to pass four parameters ‘host name, user name, password, database name’ properly then only we can successfully make connection otherwise it throws error.
  5. In html block we defined login form with input fields username, password, remind me and login button. Here when user filling details in cookie variable we stored users login information’s.
  6. If user login information wrong we can’t move to another page otherwise we storing username, password to variables ‘$username,$password’. Using select query we checks user entered login information with database table information.
  7. If not matched it throws error and returns to login form otherwise we setting username, password details on cookie till particular amount of time then that users id stored to session variable.
  8. Then we navigate to success page, here we defined select query with condition to match with session id and fetched row information stored to $row variable.
  9. Using that variable we displaying correct users name on webpage with success message and we provided logout link. When they click that link session variable sets to unset and cookies are released stored information then redirect to index page.

Conclusion :-

In conclusion we are able to know how to create login page with session and cookies using php.

First we need to start our xampp server then we load this program on browser we can see result of login page when user filled input fields and clicks login then if condition checks entered user information with database if they correct then we are navigate to home page with our name and logout option.

When filling login form if you’re not checked remind me your information will not maintain at any page otherwise session, cookie variables will had your information so we can access in all pages and when you logout session and cookie values also resets.

I hope this tutorial on PHP login page with session and cookies example helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Anjali

Experienced Computer Programmer with a broad range of experience in technology. Strengths in application development and Object Oriented architecture design, front end programming, usability and multimedia technology. Expert in coding languages such as C, C++ Java, JavaScript, PHP and more.

Follow Anjali On Linkedin 🡪