A PHP session provides an easy, but effective, way of passing variables between web pages in a PHP application. The session starts when a PHP site is accessed and ends when the user closes their web browser. Once the PHP session has been started then the developer is able to create variables that will be available to any other PHP pages that are subsequently opened. These variables are all stored in a single array - $_SESSION.
Starting the PHP Session
Some web servers will start a session automatically as soon as a PHP page is accessed (depending on the settings in php.ini). However, in most cases the session is started manually by using the session_start method:
The session_start method will:
- create a new session ID number. If required this can be read by using the session_id method, for example:This will produce an output something like:echo session_id();d4011266ba86c73b4fe8e041197f1471
- store the session variables in a file. Normally this is the system temp directory.
- pass the session id from page to page. This is done by using either cookies or, if that's not possible, as part of the URL
- read the session file (if it exists) and load the variables into the $_SESSION array
However, all that the programmer needs to be aware of is how to access the variables from each PHP web page.
Using the PHP $_SESSION Array
The PHP session's $_SESSION array can be used in exactly the same way as any other PHP array. For example variables can be read from and written to the array - in this case a session variable named passed_data is used in the file session_demo_1.php:
And, of course, that same data can be accessed from a second PHP file (the session_demo_2.php file in the first file's link):
This technique can be put to good use by keeping track of whether a user has logged on or not.
Logging on to PHP Sessions
A PHP session enables a web site programmer to restrict access to content depending on whether the user has logged on or not.This is done by:
- querying a session variable
- displaying a login page if the session variable is not set
- displaying the required information if the session variable is set
For example:
This can be used as the basis for any web page on the web site, used in conjunction with the login page (login.php) itself:
In this way the protected data will only be displayed once the user has logged on.
Summary
A PHP session exists from the time that a PHP web page is opened until the web browser is closed. It is started by using the session_start method. Once the session has been started then variables can be passed from PHP page to PHP page by using the $_SESSION array.