This blog will explain you how to create session and use session in different files. I’ll also explain how to do login and logout using session.

What is Session?

A Session basically refers to a time period for which use stays on our website. But technically its meaning is different. Session is an object which is used to store data in it and to retrieve from it. It would be accessed in entire website i.e in every pages. Session store its data on server. 

Syntax

$_SESSION["session_name"] = "Value you want to store";

Example

<?php

    session_start();

    $_SESSION["login"] = "Tarun Vaghela";

?>

I am assuming that you have already created a database and table for login with columns UserId, UserName, UserEmail, UserPassword. Enter some dummy data into it or if you want to insert data using php code please read my blog CRUD Operation in PHP with example.

Step 1: For this I created three files in C:\xampp\htdocs\ and given appropriate name to that folder. Those three files are login.php, index.php and logout.php

Step 2: Fist create a login.php file. In this file at the top of the page I started session because without starting it session couldn’t be created. So for starting session in php you have to use session_start() function. To create session you have to use $_SESSION["session_name"]. Below the code of login.php.

login.php

<?php

    $con = new mysqli("localhost","root","","sample");   /* Connection code (Connect with database) */

    session_start(); /* this is compulsory otherwise your session not work */

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Login</title>

    <style>

        input[type=text],input[type=email],input[type=password]{

            width:100% !important;

        }

        table{

            border: 1px solid rgb(202,207,210);

        }

        form {

            margin: 10% auto 0;

        }

    </style>

</head>

<body>

    <form method="post">

       <center><h1>Login Form</h1></center>

        <table align="center" border="0">

            <tr>

                <td>Email Address:</td>

                <td><input type="email" name="txtuemail"></td>

            </tr>

            <tr>

                <td>Password:</td>

                <td><input type="password" name="txtpassword"></td>

            </tr>

            <tr>

                <td colspan="2" align="center"><input type="submit" value="SignIn" name="btnlogin"></td>

            </tr>

        </table>

    </form>

    <?php

/* Login Code Start */

        if(isset($_POST["btnlogin"]))   /* Login button click event */

        {

    $res=$con->query("select * from tbllogin where UserEmail='".$_REQUEST["txtuemail"]."' and UserPassword='".$_REQUEST["txtpassword"]."'") or die(mysqli_error($con));

    if(mysqli_num_rows($res)> 0)

    {

$_SESSION["login"] = $_REQUEST["txtuemail"];

echo "<script>window.location='index.php'</script>";

    }

    else

    {

echo "<script>alert('Invalid Email or Password')</script>";

    }

        }

/* Login Code End */

    ?>

</body>

</html>

Output: Your form may look like,

Step 3: After clicking on SignIn button if you enter valid email and password than it will redirect you to the index.php and if you enter invalid email or password then you will see one popup Invalid Email or Password..!!.

index.php

<?php

    session_start(); /* Session start */

    /* Check whether session available or not. If not it will redirect to login page */

    if(!isset($_SESSION["login"]))

    {

header("Location:login.php");

    }

?>

<html>

    <head>

<title>User Login</title>

    </head>

<body>

<?php

    if(isset($_SESSION["login"]))

    {

      ?>

<center>

    <h1>Welcome : <?php echo $_SESSION["login"]; ?></h1><br/>

    <h3>Click here to <a href="logout.php" tite="Logout">Logout.</a></h3>

</center>

      <?php

    }

    else 

    {

echo "<h1>Please login first .</h1>";

    }

?>

</body>

</html>

Output: Your form may look like,

Note: In the top of the file I wrote one code that will execute when index.php file execute and it will check if there is not any session created then it redirect automatically to the login.php.

Step 4: Click on Logout link to logout from website and delete session. Create one file logout.php. In that file first start session using session_start() function then destroy session using unset(session_name) function then redirect page to the login.php page using header("Location:file_name") function.

logout.php

<?php

    session_start();

    unset($_SESSION["login"]);

    header("Location:login.php");

?> 

If you have query, please feel free to comment below. Thank you..!!