Sessions allow information to be stored during the visitor’s navigation on the site. They are often used for the authentication of a visitor, the management of a shopping cart, or any other application requiring the conservation of values between several pages.
Initializing the session variable
The session is initialized with session_start (). PHP then tries to read the identifier supplied by the user, searches for the corresponding file, and makes the information saved in the superglobal
$ _SESSION [] available to you.
Syntax: bool session_start (void)
Start a PHP Session
A session is started with the session_start()
function.
Session variables are set with the PHP global variable: $_SESSION.
Now, let’s create a new page called “demo_session1.php”. In this page, we start a new PHP session and set some session variables:
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php // Start the session session_start(); ?> <!DOCTYPE html> <html> <body> <?php // Set session variables $_SESSION["favcolor"] = "green"; $_SESSION["favanimal"] = "cat"; echo "Session variables are set."; ?> </body> </html> |
Note: The session_start()
function must be the very first thing in your document. Before any HTML tags.
Get PHP Session Variable Values
Next, we create another page called “demo_session2.php”. From this page, we will access the session information we set on the first page (“demo_session1.php”).
Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()
).
Also notice that all session variable values are stored in the global $_SESSION variable:
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // Echo session variables that were set on previous page echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>"; echo "Favorite animal is " . $_SESSION["favanimal"] . "."; ?> </body> </html> |
Another way to show all the session variable values for a user session is to run the following code:
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php print_r($_SESSION); ?> </body> </html> |
Destroy a PHP Session
To destroy the current session, just call the php session_destroy () function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // remove all session variables session_unset(); // destroy the session session_destroy(); ?> </body> </html> |
Cookies
Cookies allow you to go further, and to keep data even after the session is closed, and will be the subject of a future tutorial.