In this tutorial you will learn about the PHP Sessions and its application with practical example.
PHP Sessions are information passing mechanism that allows to make data accessible across the various pages of an entire website using the super global array.PHP session allows us to keep track of visitor across website.The main difference between a cookie and a session is that a cookie is stored on client’s computer while session variables stores on the server.
Table Of Contents−
Before using session you need to start the session and as the session starts it creats unique id (UID) for each visitor and store variables based on this UID this ID can be accessed using “PHPSESSID”.
Starting a PHP Session
1 2 3 4 5 6 7 |
<?php session_start(); ?> <html> <body> </body> </html> |
Note: The session_start() function must appear BEFORE the <html> tag
Define Session Variable
1 2 3 4 |
<?php session_start(); $_SESSION["firstname"] = "john"; $_SESSION["email"] = "john@w3school.in"; ?> |
Reading Session Variable
1 2 3 4 5 6 7 |
<?php session_start(); echo $_SESSION["firstname"]; echo $_SESSION["email"]; ?> Output: john john@w3school.in |
Destroying a Session
1 2 3 4 5 6 7 8 9 |
<?php session_start(); if(isset($_SESSION['firstname'])) unset($_SESSION['firstname']);//Unset specified session variable ?> <?php session_destroy();//Destroy the complete session ?> |