•
•0

Practical Guide to Sessions and Session Variables in PHP

ADMEC Multimedia Institute > Web Development > Practical Guide to Sessions and Session Variables in PHP

This article is going to be your Practical Guide to Sessions and Session Variables in PHP. Let’s see what some prerequisites are before we dive in.

  • You should at least know the basics of front-end development i.e., HTML5, CSS3, JavaScript this is cause it’s to be a backend developer when you don’t know what front-end is. You don’t have to be a good designer for this.
  • Knowledge of PHP like super-globals, functions, and form submission.
  • Good grasp of MySQL database.

Let’s begin then.

What is a Session?

Say you opened a website or an application clicked here and there made some changes or just explored all this qualifies as a session and you are very much in that session unless you close that website or an application.

In PHP, this session is used to record the user information which is then provided to the server so that every page of that website or an application knows who you are, what type of content you are looking for, etc. This information is recorded during login and this a common practice in e-commerce websites so that they know what you are looking for. Browsers give a unique id to every user in session so it never matches to others.

Creating a session

To start a session, we use

session_start();

function at the very top in the header. The first thing it does is look for any active session that is if you are redirected from a page if don’t find something it creates a new one. 

Note: If session_start(); is not set on top or you have misplaced it browser reports an error saying the headers are already sent. So keep this error in mind.

<?php
// session start
session_start();
?>

Creating Session Variables

After initializing the session_start(); function we are ready to use session variables wherever we want. We $session superglobal array to store the information by default its empty we can use key and value to record the data. Like following

<?php
// session starts
session_start();
  
// create session variables
$_SESSION['logged_in_user_id'] = '58548';
$_SESSION['logged_in_user_name'] =’ADMEC’;
  
// echo session variables
echo $_SESSION['logged_in_user_id'];
echo $_SESSION['logged_in_user_name'];
?>

Deleting session variable 

To delete the session variable we use the unset function simply write

<?php
// session starts
session_start();
 
$_SESSION[‘logged_in_user’]=’5846’;
 
//deleting session variable
unset($_SESSION[‘logged_in_user’]);
?>

Yup, it’s deleted you can no longer access that variable.

Destroying a session

We use session_destroy(); function when we want to completely remove all the stored information of that particular session or all session variables. First, we unset the $session then we destroy the session. This method is frequently used during log-out.

<?php
// session starts
session_start();
  
// destroy session
 
unset($_SESSION);
session_destroy();
?>

Now let’s see how we use this on the website.

This is from one of my E-Commerce projects Go Vegan based on PHP and MySQL.

First, we initialize the session.

<?php
session_start();
include '../include/connect.php';
?>
 
<!DOCTYPE html>
<html lang="en">
 
<head>
    <!-- Required meta tags-->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="Go Vegan">
    <meta name="author" content="Go Vegan">
    <meta name="keywords" content="Go Vegan">
 
    <!-- Title Page-->
    <title>Go Vegan Login</title>

Then we record the information after the user fills in the information

<?php
   if ($_SERVER['REQUEST_METHOD'] == "POST") {
       $email = $_REQUEST['email'];
       $pass = $_REQUEST['pass'];
       $sql = "select * from users where email = '$email' and pass = '$pass'";
       $run = $work->allquery($sql);
       $rows = $run->num_rows;
       $result = $run->fetch_array();
       if ($rows > 0) {
           $_SESSION['email'] = $email;
           $_SESSION['id'] = $result['id'];
           header('location:../index.php');
       } else {
           echo "Login Failed Check Credentials";
       }
   }
   ?>

Here we are first checking if the user exists if it does then we are storing the information and redirecting the user to the main homepage of the site.

<?php
session_start();
 
$userId = $_SESSION['email'];
$ID = $_SESSION['id'];
 
if (!$userId) {
    header('location:loginFiles/login.php');
}

Now, here we are checking if the user has logged in if not then the header function redirects to the login page again.

You might be wondering what if the user doesn’t want to log in or what if this is first-time.

Let’s look at this in order.

Skip Login

<?php
session_start();
include '../include/connect.php';
$sql = "select * from users where email = 'guest'";
$run = $work->allquery($sql);
$rows = $run->num_rows;
$result = $run->fetch_array();
if ($rows > 0) {
    $_SESSION['email'] = "guest";
    $_SESSION['id'] = "ewgrwgegr";
    header('location:../index.php');
}

Note: here we are manually feeding the information and then when this redirects to the homepage it only checks if the id exists and it does hence, the user will be able to explore the site without any problem.

We can also use this method to store information in the cookie say a guest user added a product in the cart that product information is then stored in the cookie and when the user signs in or signs up the product gets directly transferred to the user cart.

Sign Up

<?php
session_start();
include '../include/connect.php';
?>
<?php
   if ($_SERVER['REQUEST_METHOD'] == "POST") {
       $fname = $_REQUEST['fname'];
       $lname = $_REQUEST['lname'];
       $name = $fname . ' ' . $lname;
       $dob = $_REQUEST['dob'];
       $gender = $_REQUEST['gender'];
       $email = $_REQUEST['email'];
       $phone = $_REQUEST['phone'];
       $pass = $_REQUEST['pass'];
   
       $img = $_FILES['img'];
       $imgName = $img['name'];
       $tmp = $img['tmp_name'];
       $imageFileType = $img['type'];
   
       if ($fname != "" && $lname != "" && $dob != "" 
             && $gender != "" && $email != ""     
                && $phone != "" && $img != "" && $pass != "") {
           if (
               $imageFileType != "image/jpg" && $imageFileType != "image/png" 
                   && $imageFileType != "image/jpeg"
           ) {
               echo "Sorry, only JPG, JPEG, PNG files are allowed.";
           } else {
               $sql = "INSERT INTO `users` (`name`, `phone`, `email`, `pass`,
                 `address`, `pin`, `alphone`, `img`, `status`, `state`, 
                 `city`, `dob`, `gender`) VALUES ('$name', '$phone'
                  , '$email', '$pass', NULL, NULL, NULL,
                  '$imgName', '1', NULL, NULL, '$dob', '$gender')";
               if ($work->allquery($sql)) {
                   move_uploaded_file($tmp, '../admin/img/user/' . $imgName);
                   header('location:login.php');
               } else {
                   echo "Account Exist";
               }
           }
       } else {
           echo "Wrong Input!!!";
       }
   }
   ?>

Here we are first checking if the user is giving the right type of information then we check if he already exists if it doesn’t then a new user gets created and again redirected to the login page.

This is pretty basic validation you can make your site more secure by a more high level of security.

So, this is all related to sessions and session variables in PHP.

Learn PHP with Experts at ADMEC

If you want to learn more about the PHP and MySQL here are some of the best courses available:

For more information, you can contact us or if you need one to one guidance call us at 9811818122 or 9911782350. 

Related Posts

Leave a Reply

Call Now