Simple Session management in PHP

 Hi There,

In this tutorial you will learn how to manage session in php.

What is session?

Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data. The absence of an ID or session cookie lets PHP know to create a new session, and generate a new session ID. 
 
when you start session in php it will store in tmp folder.

A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

PHPSESSID is an auto generated session cookie by the server which contains a random long number which is given out by the server itself.
 
I will show a simple example to understand  session management.

Step1: Create index.php and copy paste below 

index.php contains simple login form and session.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    </head>

    <body>
    <?php 
    session_start();
    if(isset($_SESSION['name'])){
    echo "Welcome ".$_SESSION['name'];
    echo '<br>';
    echo '<a href="logout.php">Logout</a>';
    }else{?>
    <form action="logging.php" method="post" enctype="application/x-www-form-urlencoded">
    <input type="text" name="username" placeholder="username" /><br />
    <input type="password" name="password" placeholder="password" /><br />
    <input type="submit" name="submit" value="Login" />
    </form>
    <?php } ?>
    <script>
    <?php 
    if(isset($_GET['msg'])){
    ?>
    alert('<?php echo $_GET['msg']; ?>');
    <?php
    }
    ?>
    </script>
    </body>
    </html>
 
 Step2: Create logging.php and copy paste below 

logging.php file contains session and login authentication
    
 <?php
    ob_start();
    if(isset($_POST['submit'])){
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
        if($username == "admin" && $password == "pass"){
            session_start();
            $_SESSION['name']= $username;
            header("Location: index.php?msg=Loggedin successfull");
        }else{
            header("Location: index.php?msg=Invalid Username or Password");
        }
    }
    ?>
 
 
 Step2: Create logout.php and copy paste below
 
 
 
 
    <?php
    session_start();
    if(isset($_SESSION['name'])){
    unset($_SESSION['name']);
    session_destroy();
    header("Location: index.php?msg=Loggedout successfully");
    }
    ?>
 
 
 
Happy Coding!

Comments