How to login and logout a user using PHP cookies

How to login and logout a user using PHP cookies simply deals with setting of cookies on logging in and unsetting of cookies on logout.

What are cookies

Cookies are some data stored on users computer to recoginze the user. Cookies are used because http protocol is stateless protocol and does not know what happened in time before. So for applications like keeping a user logged in to your website as he browses to different pages, cookies are used.

Creating cookies

Syntax:

setcookie(name, value, expire, path, domain, secure, httponly);

Only name parameter is required. rest all are optional

Creating your first cookie

<?php 
  $cookie_name="user";
  $cookie_value="Scanfcode";
  setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>

Retrieving cookie

<?php 
  if(isset($_COOKIE['user']))
  {
       echo "Cookie '" . $cookie_name . "' is set!<br>";
       echo "Value is: " . $_COOKIE[$cookie_name];
  }
?>

if(isset($_COOKIE['user'])) is used to check if the cookie is set. isset
check the stated.

How to login and logout a user using PHP cookies

Before we continue this please refer to the post Creating a login script in php. This is a continuation to that topic.

Repeating this code from Creating a login script in php

    <?php
      if(isset($_POST['submit'])) //avoid error:undefined index
      {
          $email=$_POST['email']; //getting values from the form
          $password=$_POST['password']; 
      }
      define("HOST", "localhost");     // The host you want to connect to.
      define("USER", "user_db");    // The database username. 
      define("PASSWORD", "123$%bb^7aqq!2");    // The database password. 
      define("DATABASE", "sample_db");    // The database name.
      $connection = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
      if (mysqli_connect_errno())
       {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
       }
      if($email="" ||$password="")
      {
        echo "Please enter a valid value to each input";
      }
      else
      {
        $sql="SELECT * FROM `adminlogin` WHERE `password`='$password' WHERE `email`='$email'";
        $run=mysqli_query($connection,$sql);
        $count=mysqli_mun_rows($run);
        if($count>=0)
        { 
            echo "Login successful";
        // ------------------- additional code to set cookie ----------//
          $cookie_name="user";
          $cookie_value=$email;
          setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
        //---------------------------------------------------------//
        }
        else
        {
            echo "Login unsuccessful";
        }
     } 
    ?>

In this code we are storing the value of email id used by the user to login as a cookie with name user.

Creating a logout script

Let us say when the user click logout this script should run.

Creating a logout link

<a href="logout.php">Logout</a>
<pre>
Now creating <strong>logout.php</strong>. This file is simply unsetting the cookie named user set during login. The code will be
<pre>
 <?php
   if (isset($_COOKIE['user'])) {
    setcookie("user", "", time() - 3600);
    echo "<script>location.assign('index.php')</script>";  //redirection
   }
?> 

setcookie("user", "", time() - 3600); sets the expiration date of the cookie to one hour ago ,also its sets the value of cookie to empty.

location.assign('index.php')"; this line redirects the user to index page after logging out.

Leave a Reply

Your email address will not be published. Required fields are marked *