|
|
|
|
How to use $_SESSION variable in PHP
Using $_SESSION instead of Cookies. Tutorial on how create and use $_SESSION in PHP.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1.
|
|
|
$_SESSION variable stores data on a web server for each user separately, which makes data accessible from other php pages as well.
First thing you need to do to use $_SESSION variable is put this in the very first row of your code:
<?php session_start(); ?>
|
|
|
2.
|
|
|
Now enter the following code in index.php:
<?php $_SESSION['x']='John Deer';
echo $_SESSION['x']; ?>
First we store in $_SESSION['x'] value 'John Deer' and function echo displays the variable value.
|
|
|
3.
|
|
|
This is what you get in your web browser if you you open index.php.
|
|
|
4.
|
|
|
Now open a new document in the same folder and save it as index2.php.
Again put the following code in the very first row of the new index2.php document:
<?php session_start(); ?>
|
|
|
5.
|
|
|
Inside the <body> tag enter the following code:
<?php echo $_SESSION['x']; ?>
In this case we didn't define the variable value, we just displayed the existing value of $_SESSION['x'] variable.
|
|
|
6.
|
|
|
Now try and open index2.php in your browser and you should be able to see value John Deer displayed. Meaning the $_SESSION['x'] variable value has been successfully transferred from the index.php to index2.php page.
Variable $_SESSION gets automatically deleted after about 15 minutes of user inactivity.
In case you want to create another $_SESSION['x'] variable, just put in some other letter instead of an x.
|
|
|
|
|
|
|
|
|
|