1. Home
  2. Computing & Technology
  3. PHP / MySQL

Basic PHP Sessions

By , About.com Guide

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];
?>
Explore PHP / MySQL
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. Advanced PHP
  5. PHP Session Variables - PHP Sessions Tutorial - Learn PHP Session Variables

©2009 About.com, a part of The New York Times Company.

All rights reserved.