Handling Session using PHP

Here I am going to explain you how we maintain our session in PHP application with the help of login example, before we start learning how to handle session we have to know what session is and what is the difference between session and cookies.

A session is a simple way to store some useful information like username, shopping cart etc for individual user against a unique session ID. This can be used throughout the application till the user doesn't close the browser. The session is not stored on the users computer it store on the server because HTTP doesn't maintain the state so we use session for maintaining the state of the user where as cookies are stored on the user computer. 

Starting a PHP Session:
We can start a PHP session easily by calling session_start() funtion. This function first check if a session is already started or not, if session is not started then it starts the session you have to call session_start() function at the beginning of the page.

How we store and get session variables:
Session variable are stored in an array called $_SESSION[] these variables can be accessed during lifetime of a session.
Example:   $_SESSION['login_user']=$user_name;

Note: Before setting session variable we can use isset() function to check if session variable is already set or not.

To get session variable use $user=$_SESSION['login_user'];

How we destroy session:
To destroy session use the below code
<?php
session_start();
// remove all session variables
session_unset();
// destroy the session
session_destroy()
?>

Demo Example:

Step1: Create a database
          create database employee;
           create table login
           create table login
           (
                username varchar(50) primary key,
                password varchar(50)
           );

           insert data into login table
           insert into login values('Administrator','admin');


 Step2: config_db.php


<?php
         $link = mysqli_connect("localhost", "username", "password", "employee");  
         // Check connection
         if($link === false){
                die("ERROR: Could not connect. " . mysqli_connect_error());
         }
?>


 Step3: index.php

<?php
       include("config_db.php");
       session_start();
       if($_SERVER["REQUEST_METHOD"] == "POST")
      {
           $user_name=($_POST['username']);
           $user_pass=($_POST['password']);
 
         $sql="select * from login where username='$user_name' and password='$user_pass'";

           
         $result = mysqli_query($link,$sql);
           

         $row=mysqli_fetch_array($result);
           

         $count=mysqli_num_rows($result);

           // If result matched $myusername and $mypassword, table row must be 1 row
           if($count==1)
          {
                 $_SESSION['login_user']=$user_name;
                 header("location: welcome.php");
          }
          else
          {
                $error="Invalid user name or password";
          }
     }
?>      


<html>
<head>
           <title>Login Form</title>
</head>
<body> 

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
            User Name:<br/>
             <input type="text" name="username"/><br/>
             Password:<br/>
            <input type="password" name="password"/><br/><br/>
            <input type="submit" value="Login"/><br/>
    </form>


 </body>
</html>

Step4: check_session.php

<?php
        include('config_db.php');
        session_start();
        $user=$_SESSION['login_user'];


     $sql_query=mysqli_query($link,"select username from login where username='$user' ");

        $row=mysqli_fetch_array($sql_query);

        $login_session=$row['username'];

        if(!isset($login_session))
       {
             header("Location: index.php");
       }
?>


Step5: welcome.php

<?php
         include('check_session.php');

?>
<html>
<head>
<title>Welcome</title>
</head>
<body>
      <h1>Welcome <?php echo $login_session; ?></h1>
      <form action="logout.php">
                <input type="submit" value="Logout"/>
      </form>
</body>

</html>

Step6: logout.php

<?php
       session_start();
       // remove all session variables
       session_unset();

      // destroy the session
      if(session_destroy())
     {
            header("Location: index.php");
     }
?>



Download Project




Note: If you have any problem then drop a comment below i will help you or if you like my post then subscribe my website to get my new post directly in your email inbox.



Post a Comment

3 Comments