PHP Access Session Data

In this chapter you will learn:

  1. Reading and Writing Session Data
  2. Store class object
  3. Example - Checking Session Data
  4. Example - Removing Session Data
  5. Example - Storing Complex Data Types

Reading and Writing Session Data

You store all your session data as keys and values in the $_SESSION[] superglobal array.

So you might store the user's first name using:

$_SESSION["firstName"] = "Jack";

You could then display the user's first name - whether in the same page request or during a later request - as follows:

echo( $_SESSION["firstName"] );

You can store any type of data in sessions, including arrays and objects:


<?PHP
$userDetails = array( "firstName" =>   "Jack", "lastName" =>   "Smith", "age" =>  34 ); 
$_SESSION["userDetails"] = $userDetails;   
?>

Example 1

To store objects, make sure you include your class definitions or class definition files before retrieving the objects from the $_SESSION array.


<?PHP/*from  jav  a2s . c  om*/
           session_start(); 

           class MyEmployee { 
             public $firstName; 
             public $lastName; 
           } 

           if ( isset( $_SESSION["user"] ) ) { 
             // Make sure the MyEmployee class is defined by this point 
             print_r( $_SESSION["user"] ); 
           } else { 
             $user = new MyEmployee; 
             $user->  firstName = "Jack"; 
             $user->  lastName = "Smith"; 
             $_SESSION["user"] = $user; 
           }    
?>

Example 2

You can check whether a variable has been set in a user's session using isset().


<?PHP//from   j ava 2  s .  c o  m
      session_start();
      if (isset($_SESSION['FirstName'])) {
             /// your code here
      }
?>

To view the session data.


<?php/*ja  v  a 2 s  . c om*/
session_start();

if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>

Example 3

Using the function unset() to remove a specific value from a session.

To extend the previous script to remove data, use this:


<?PHP/*from java2s  .  c o m*/
      $_SESSION['foo'] = 'bar';
      print $_SESSION['foo'];
      unset($_SESSION['foo']);
?>

Example 4

You can use sessions to store complex data types such as objects and arrays.


<?PHP/* j a va2 s  . c  om*/
     $myarr["0"] = "Sunday";
     $myarr["1"] = "Monday";
     $myarr["2"] = "Tuesday";
     $myarr["3"] = "Wednesday";
     $myarr["4"] = "Thursday";
     $myarr["5"] = "Friday";
     $myarr["6"] = "Saturday";

     $_SESSION["myarr"] = $myarr;

?>

Next chapter...

What you will learn in the next chapter:

  1. Destroy Session
  2. Destroy Session Array
  3. Destroy Session Cookie
Home » PHP Tutorial » PHP Session
PHP Session
PHP Access Session Data
PHP Destroy Session
PHP Session Behavior