Session in PHP

Spread the love

What is Session?

Session in PHP is used to store the information on the server which can be accessed at any page in your web application. Session store data on the server, unlike cookies which store data on client’s machine.

Session data are stored in a file and that file resides on the server in a temporary directory. You can set the location of that temporary file on the server by setting the value of session.save_path in php.ini file.

Using session in PHP:

We can use session in PHP by following certain steps:

To set session we have to first start the Session in PHP and then only we can use session.
To start a session you have to use the session_start() function. This function will check if the previous session has been already started or not. If not then it will start a new session.

Setting session variable:

Session variable can be directly store in superglobal array $_SESSION[].

Example: $_SESSION[‘username’] = ‘sam’;

We can access session variable using $_SESSION array directly.

Example: echo “Username stored in session – “. $_SESSION[‘username’];

Note: session_start() function always need to be called at the begining of the page. To check session present use isset() function.

Example:

<?php
     session_start();

     if(isset($_SESSION['username']))
     {
          echo "Welcome ".$_SESSION['username'];
     }
     else
     {
          echo "Please login to continue.";
     }
?>

You can set as many session variables as you like using the above procedure.

Deleting Session:

There are two ways you can delete the session.

  1. By using session_destroy() function. We can delete all the session variable which set in $_SESSION using session_destroy();
  2. By deleting individual session variable using unset() function. You have to pass individual session variable in unset() function.

Before deleting the session we always need to start the session. So in above examples,

<?php
     session_start()
     session_destroy();
?>

<?php
     session_start()
     unset($_SESSION['username']);
?>


Spread the love

Leave a Comment