What Are Sessions And How Do They Work With PHP

What Are Sessions And How Do They Work With PHP

Hi Friends, I’ve come back after a long time on your blogaddition. Actually I couldn’t write due to some of my technical works (was busy with developing my new video website way2clip.com) but now I’ve decided to be regular on it and write as much as possible for my readers. Today I’m not writing a programming tutorial with any kind of source coding but this post will clear all the confusions about “what are session and how do they work”. I’ve used the phrase “Work with PHP” that means sessions are managed with each web programming or scripting language but in this article I’ll talk only about Sessions In PHP.

What Are Sessions And How Do They Work With PHP

The only thing about sessions most of the programmers (not talking about experts because I’m not an expert also) know is that sessions are server side storage system. Yes, there is no any doubt but is it enough to know about sessions? People who prepare their technical interviews never read full about sessions and not be able to give the proper information about them. Some people relate sessions completely with cookies but it’s not. I’ll elaborate anything that how session are related with cookies and not completely dependent on them. So take a breath and start reading about… :P :)

What Are Sessions??

A logical approach that let any application store a huge amount of data on server side and make this available through out the whole application, is called session. Sessions are not any language specific but can be used in any programming logic. Haven’t got??. Sessions are some kind of data storage files located on the server (usually php/tmp directory on server and can be configured also in PHP.INI file) that are used to retain the stored data on each HTTP request a client makes for. For example, suppose, you want your users to be authenticated on your application in order to view certain web pages by requiring them to provide their user identity (username and password). Does it make sense as if your users send their identity with each page url and let the application authenticate them for that particular web page?? They will abuse both you and your worst application.

Sessions Come In The Action Here

Is it not pretty good, if we authenticate our users only once at the login time and then store their common information in a particular file (session file) for a certain time period (depends on your configuration). Creating sessions make our application very much flexible and secure as the users don’t need to put their user identity in the page url or in hidden inputs again and again.

How Sessions Work With PHP

I know some of you are still confused and haven’t got very much about sessions. So I explain each and everything by taking a little php source code and tell how sessions work with php applications. PHP has some session handling functions and we will use some of them in our example.

Let’s have a look at the following very simple Login Example Code:

$query = mysql_query("SELECT * FROM `users` WHERE `username` = '$username' AND `password` = '$password'");
if($result = @mysql_fetch_object($query)) {
session_start();
$_SESSION['userid'] = $result->id;
$_SESSION['username'] = $result->username;
$_SESSION['email'] = $result->email;
} else {
header("Location:login.php");
}

Create The Session Using session_start()

The very first line of above code tries to get the user from database using username and password entered by end user. If it finds this a valid user, the PHP function “session_start()” executes else redirect to login again. What does this function do? This function starts the session and creates a unique identifier for that particular session which is a random string (called session identify string or session id) of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443. A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443. At the same time a temporary cookie called PHPSESSID is also set to your user’s browser to store unique session identification string. After starting the session you can store the session data using PHP’s Global Session Variable $_SESSION as shown in above code.

Note: You must have to start the session on first line of each page to make the use of session globally.

How PHP Identifies And Reads Session Files?

When the browser makes any HTTP request to the server for a particular resource or web page, the request carries some HTTP Request Headers with it. Headers include the PHPSESSID cookie also that was generated during the session creation. When the request reaches at the page, session_start function (included on top of the page) starts the session and tries to generate a new unique identifier string as we discussed above but before doing this it checks if any PHPSESSID cookie is present (using $_COOKIE variable) in the http request. If it finds any then looks in server temporary directory for the file bearing that name and a validation can be done by comparing both values. After finding the valid session file for that particular session you can get all stored session variables using $_SESSION also.

Destroy The Session session_destroy()

session_destroy() is usually executes on the log out files of an application to destroy both the session cookie and session file located at server session directory. After destroying the session, your application will be no longer able to read session variables.

You should have a look at the following useful PHP Session Configuration Options that can also be customized in your PHP.INI file.

Session Cookie Options:

As we discussed above PHPSESSID is called the session cookie that helps your application to find out the session file on the server for this cookie. This is a temporary cookie (that has zero lifetime)  automatically destroyed or deleted when user closes his browser. So the user has to re-log into the application to start a new session.
Basic Cookie Options For Session
1. session.use_cookies : this option specifies whether your whole application will use cookies to store the PHPSESSID on the client side (browser) or you pass it with url on each request. This option takes Boolean values (1 or 0). By default it is enabled.
2. session.use_only_cookies :  This option takes also a Boolean value and specifies whether your application will identify the session file only by using cookies or not. By default it is enabled.
3. session.cookie_lifetime : This is the lifetime (by default zero) for your PHPSESSID cookie that means it will be deleted when a browser is closed. You can increase it in seconds to prevent the session destroy on browser closing.

Garbage Collection:

PHP provides a garbage collection functionality with the function session_gc(). This function executes on each session_start() call. session_gc considers all the session data as garbage and destroys the session if no activity has been done by the user in a certain period of time. This time is 24 minutes by default and can be configured changing the option session.gc_maxlifetime value in INI file.

Important: Do not get confused with session cookie life time and garbage collection life time. Both are different to each other. Suppose you configured your garbage collection life time as 30 minutes and PHPSESSID cookie (can also changed by configuring session.name) life time as 60 minutes. A user just logged into your application and immediately closed the browser and went to take his lunch. Now when he comes back within 30 minutes and opens this browser, he will find the session as it is because he did not exceed the garbage collection life time. But if he comes after 30 minutes and opens the browser he will get session destroyed even his session cookie life time is 60 minutes. It means session garbage time has much priority than cookie life time.

PHP Session Handling Functions:

It is not necessary to have the session id in cookies as we have seen that PHP.INI has an option to configure it. You can configure session.use_cookies as 0 and store the PHPSESSID in the database for that particular user for the security reason or prevent session hijacking with XSS attacks. You can use session_set_save_handler() function to create a set of user-level storage functions.  Create your own session handling functions like sessionOpen(), sessionClose(), sessionGet() and register them in session_set_save_handler(). For example call sessionOpen() function on top of each requested page that will get the PHPSESSID value from database each time and then will identify the session file. To understand this more, search for the term “php session database handler” on google.

Information: The most common PHP interview question that is asked many times is “Will session work if cookies are disabled in the browser?” and most of the people answers this as “No”. This is not absolutely correct as it depends on your session configuration in INI file whether to use cookies or not.

Enjoy…. Now I think you have gained a little knowledge about “What are sessions and how do they work”.

One Response to “What Are Sessions And How Do They Work With PHP”
  1. Nitin says:

    Good very lengthy…….

    So, Make me bore….

    Write something which is not boring, can say interesting type…..

Leave a Reply

Manish Jangir - Find me on Bloggers.com