1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Basic PHP Sessions

By

2 of 3

Using Session Variables
Now we are going to make a second page. We again will start with session_start() (we need this on every page) - and we will access the session information we set on our first page. Notice we aren't passing any variables, they are all stored in the session.

Call this code mypage2.php

 <?php 
 // this starts the session 
 session_start(); 
 
 // echo variable from the session, we set this on our other page 
 echo "Our color value is ".$_SESSION['color']; 
 echo "Our size value is ".$_SESSION['size']; 
 echo "Our shape value is ".$_SESSION['shape']; 
 ?> 
All of the values are stored in the $_SESSION array, which we access here. Another way to show this is to simply run this code:
 <?php 
 session_start(); 
 Print_r ($_SESSION);
 ?> 
You can also store an array within the session array. Let's go back to our mypage.php file and edit it slightly to do this:
 <?php 
 session_start(); 
 
 // makes an array 
 $colors=array('red', 'yellow', 'blue'); 
 // adds it to our session 
 $_SESSION['color']=$colors; 
 $_SESSION['size']='small'; 
 $_SESSION['shape']='round'; 
 print "Done";
 ?> 
Now let's run this on mypage2.php to show our new information:
 <?php 
 session_start(); 
 Print_r ($_SESSION);
 echo "<p>";

 //echo a single entry from the array
 echo $_SESSION['color'][2];
 ?> 
  1. About.com
  2. Technology
  3. PHP / MySQL
  4. Advanced PHP
  5. Using PHP Session Variables - Tutorial

©2014 About.com. All rights reserved.