BANGALORE, INDIA: Just by typing the HTTP address on the address bar of a web browser doesn't maintain the state of the user while browsing. In online shopping for instance, at the end of checkout, when you are, let's say on the 7th page, the system makes the list of the items that were selected on the 3rd page of the website.
This is made possible because the website keeps track of the entire user session. This funtionality can be added to a website by using the 'Session' feature of PHP. It basically saves the state of a particular user while the user is traversing through website. Sessions are like cookies with the major difference that they save the state on the server whereas cookies are stored on clients. This means that sessions are more secure than cookies, as the information is not exchanged between server and client.
|
Direct Hit!
|
Applies To: PHP developers
USP: Maintaining user
information in online shopping
Primary Link: www.php.net
Keywords: PHP session |
The session information, ie the state of a user is temporary element, which is later deleted from the server after the user leaves the website. The state is associated with a particular user having a unique user ID which is stored on the cookies or propagated through URLs.
Creating a PHP session
For every start there is an end, likewise in sessions you have to create a session and finally terminate it after the work is done. To create a session you need to call 'session_start()' function, which will be placed before the HTML code starts. Because no information can be stored until a session is created. Code for creating a session is as follows:
<?php
session_start();
?>
<html>.... ....</html>
After the required function is called, a session ID is created and stored in the cookies on the client machine. The default file name of the cookie is 'PHPSESSID' and can be changed to any file name simply by making minute changes in PHP configuration file, ie php.ini. If you want to know the client's session ID then simply add the following line inside the 'HTML' tags:
print $PHPSESSID;
What if a user goes to the next page, which also calls the function 'session_start().' PHP checks whether a session has already been started on the client machine for the same website. If yes then it ignores the 'session_start()' function call on the second page.