<?php
session_start();
session_unset();
Can I Store An Array In A Session?
Sure, this is simply done in the same way as setting regular variables.
Let’s create a new page1.php with the following code:
Listing 11 page1.php
<?php
session_start();
$my_array=array('cat', 'dog', 'mouse', 'bird', 'crocodile', 'wombat', 'koala', 'kangaroo');
$_SESSION['animals']=$my_array;
echo 'Putting array into a session variable';
?>
Now that we have the array $my_array in a session variable called $_SESSION['animals'] we can have a look through the array as we choose. Use this snippet to create a new page2.php file:
Listing 12 page2.php
<?php
session_start();
foreach($_SESSION['animals'] as $key=>$value)
{
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
?>
The result of the above code will show you the session array, with the array keys.
Listing 13 Browser output from page2.php (listing-13.txt)
The value of $_SESSION['0'] is 'cat'
The value of $_SESSION['1'] is 'dog'
The value of $_SESSION['2'] is 'mouse'
The value of $_SESSION['3'] is 'bird'
The value of $_SESSION['4'] is 'crocodile'
The value of $_SESSION['5'] is 'wombat'
The value of $_SESSION['6'] is 'koala'
The value of $_SESSION['7'] is 'kangaroo'
You could of course, simply choose individual array members if your page2.php file looked like this..
Listing 14 page2.php
<?php
session_start();
Can I Store An Object In A Session?
Yes, using the following code we can include our class file as we would for any class. In page1.php we will instantiate a new object and put it in a session variable. Let’s us create a simple class file to include in our page1.php and page2.php scripts, we shall call it myclass.php.
Listing 15 myclass.php
<?php
class mySessionClass{
function __construct(){
}
function bar(){
return 'foo';
}
}
?>
In page1.php we include the class file and instantiate a new instance of the class directly into a session variable.
Listing 16 page1.php
<?php
include('myclass.php');
session_start();
$_SESSION['foo']= new mySessionClass;
echo 'Setting value of foo to an object';
?>
Now we have the object in a session variable, we can go on to page2.php and use methods from mySessionClass.
Listing 17 page2.php
<?php
include('myclass.php');
session_start();
Can I Store A File Pointer In A Session?
The short answer is NO. Let’s create a page1.php and page2.php and see what happens. page1.php will look like this:
Listing 18 page1.php
<?php
session_start();
$fp = fopen('my_file.txt', "r");
$_SESSION['filePointer'] = $fp
?>
<a href="page2.php">link to page 2</a>
Everything here is fine. the variable is set and no error should be seen. page2.php should look like this:
Listing 19 page2.php
<?php
error_reporting(E_ALL);
session_start();
$contents = fread ($_SESSION['filePointer'], filesize ($filename));
fclose ($_SESSION['filePointer']);
echo "Contents: $contents"
?>
The above code will produce an error similar to this:
Listing 20 The warning caused by trying to store file pointers in sessions (listing-20.txt)
Notice: Undefined variable: filename in /html/page2.php on line 10
Warning: fread(): supplied argument is not a valid stream resource in /html/page2.php on line 10
Warning: fclose(): supplied argument is not a valid stream resource in /html/page2.php on line 13
Contents:
As you can see, no success on storing the file pointer.
echo $_SESSION['foo']->bar();
?>
Important Note: You MUST include the class definition on every page when you store an object
echo $_SESSION['animals'][3];
?>
This would simply retrieve the value for the 4th member of the array and print bird.
session_destroy();
?>
How Are Sessions Stored?
The default behaviour for session storage is to save the session data in a file. This behaviour can be altered by changing the session.save_handler in your php.ini file. Options can be
As we saw earlier the format of saving session data in files looks like this:
Listing 21 Session data as stored on the filesystem (listing-21.txt)
|s:3:"bar";bar|s:3:"foo";foobar|s:5:"fubar";
If we choose we can have this stored in one of the options above.
The mm option saves the session data into memory, this also gives
significant speed increase and is often recommended by tutorials for
fine tuning PHP and apache web server.
Sessions may also be stored in a database. This option provides for
greater manageability of sessions and allows the programmer to perform
tasks such as counting of active sessions etc.
With the advent of PHP5, we now have SQLite bundled with PHP. If PHP is configured —with-sqlite, you will have access to saving sessions with a PHP native database, although SQLite is not truly a database, but a file abstraction layer with and SQL interface.
When Do Sessions Expire?
The default behaviour for sessions is to keep a session open
indefinitely and only to expire a session when the browser is closed.
This behaviour can be changed in the php.ini file by altering the line:
Listing 22 Keeping a session alive indefinitely (listing-22.txt)
session.cookie_lifetime = 0
If you wanted the session to finish in 5 minutes you would set this to:
Listing 23 Keeping a session alive for five minutes (listing-23.txt)
session.cookie_lifetime = 300
Remember to restart your web server after making this change.
How Can I Send Headers Then Start A Session?
Earlier we mentioned that you cannot send anything to the browser before session_start(). This is because when you set a header, you cannot do it twice. When you send text to the browser, headers are sent also.
However, PHP does provide a method to set headers, send text, and still be able to start your session. The ob_start() function allows you to buffer your output till you are ready to send content to the browser.
Listing 24 ob.php (listing-24.php)
<?php
error_reporting(E_ALL);
ob_start();
header ("Pragma: no-cache");
echo 'This is a line of text';
session_start();
$_SESSION['foo']='bar';
ob_end_flush();
?>
Run this snippet of code and it will output the text
Listing 25 Browse output from using output buffering (listing-25.txt)
First we sent a header with the no-cache, then echoed some text and finally started a session and set a session variable.
Session Security
This has a been an often debated point against the use of sessions.
The reality is that a session, like any other programming method, will
be as secure as you make it. With the advent of session came new ways
in which a malicious user could hijack your session and your identity.
It is beyond the scope of this introduction to go in-depth into
session security and is left as an exercise to the reader to hunt out
resources for session security. An excellent place to begin is this
fine article on PHP session security, and of course there is always, the PHP manual.