PHP is one of the most popular and widely used Server side scripting language. Session handling is one of the key thing which most of web applications and projects need.
Suppose you are building one E-commerce site, to allow any one to buy the product you must ask them to log-in with their user name and until they log out your system must track the user in every step, this concept is called as “session tracking”.
Now why do we need to track the session, answer is very simple. HTTP is state less protocol, and when you refresh the page, it lost everything, which your project should not !
To handle session in PHP, only thing we gonna need is $_SESSION global variable. That’s it. Oh yes with couple of in built function too.
You can get lot’s of Syntax based tutorial on web, so i am not gonna do that, instead i will be explaining it with the live demo, so that you can easily understand the working and concept of session tracking in PHP.
Have you ever tried to access your Facebook profile without Log in, Try once and it will redirect you to log in page. How it is done, well it is session handling only. I am going to built one simple Log in and profile system in that we have two files called login.php and profile.php.
To access profile.php, user must log in first and log-in name will be used until log out or browser close (session terminate when browser closed).
Before showing you code, let me tell you some in built PHP functions which comes handy in session tracking.
To handle session, you must first start it and store some value to any session variable. You can create any amount of session variable you wish. To validate whether Session is active or not, we use isset() function and finally to destroy it we use unset() function.
Here is our login.php:
//Storing the name of user in SESSION variable.
<title>Session Handling in PHP - CodeforGeek Demo's</title>
<form action="" method="post" id="main_form">
<input type="text" name="user_name" size="40"><br />
<input type="submit" value="Log in">
After submitting the form, we are storing the name of user in session and in next page we are going to use the same name. This is how most of web projects do. Now here is a code for profile.php.
<title>Profile of <?php echo $name;?></title>
<h1>Hello <?php echo $name;?></h1>
<h3><a href="logout.php">Click here to log out</a></h3>
In this file, first we are checking whether the SESSION is set or not. If not then we will redirect the user to main page, else we will store the name of user into variable and displaying it in HTML code.
Finally we let user log out from system and to do here is a code.
You can view the live demo of this simple session handling in PHP or download code from Github.
Whats next ?