Bubble.ro - because there is always something new to learn about

Creating a customized session handling system in PHP (part I)

 

Category: Programming/PHP

They are used on most websites, yet very few people know they even exist. They use various technologies like "cookies", "SQL", but not many know they can create their very own session handling systems to handle their own need. I will try to explain the technology behind the sessions and very much how to get your own sessions up and running.

What are sessions?


Basically sessions are containers which hold information on the server, each visitor being associated a unique session identified by a session id.

A session has to respect some rules:

 - Encapsulation: a session must be able to support a fixed or variable number of variables which can be set or modified.

 - Persistence: session data must be available for access after browser reload (or several page reloads).

 - Security: data encapsulated within a session must NOT be able for access by unauthorized users, be it remote, local users or even a user with another session. Also, sessions should be removed when a visitor leaves the website. Still, this is not exactly possible to detect since browsing does not use a continuous connection, so the only solution is to remove the session data after the current session expires.

 - Availability: data stored in a session must be available for read/write at any time during a running script.

PHP standard sessions


PHP has its own session handling functions built-in which programmers can use, and in some cases they are just what you need. Still, they lack some features which might be useful and one of the most important aspects would be that they "mess up" links pretty badly. They are still fully functional, of course, but you sometimes see a &PHPSESSID=[...] at the end (or something similar).

This happens because the standard PHP session library uses two ways of passing the session id:

- First it adds the PHPSESSID variable to each URL, which is then checked when the page is reloaded.

- Additionally is tries to use cookies as well, setting the PHPSESSID as well through cookies. If on the page reload is reads successfully that variable is uses only that, dumping the link alteration. If not, it continues to add the variable to all URL-s.

Now, for a normal user this is not bad since links will normally look as they should, plain and simple after the first reload/page change so they can pass over them to friends without looking too suspicious. The real problem is when a search engine spider is trying to index your website. Since they don't accept cookies, all links that they collect will contain the session id in the URL as well. It is true that some search engines know how to eliminate them, but still they don't work too well in all cases and it's definitely not something to count on.

The standard session handling system uses plain files to store session data, which can present some advantages, but as well some disadvantages as well. One of the advantages would be that you can store a variable number of variables inside them, without having to worry on their type or size. Still, this means that the system has to create files each time a session is created and delete them when sessions expire. Although these are simple file operations and are usually handled by the operating system, it might be more efficient if a database is used instead.

Database used for storing sessions


One of the features if you want of using a database for storing sessions would be the flexibility which is given by the SQL driven operations and the access to all session data (although this might be seen as a security breach, remember that it depends on the programmer to give permission to view/modify data for other users ONLY to authorized people). For example, we can view a list of all active sessions by simply performing a SELECT operation on the sessions table.

Another advantage is that you can design your own sessions table structure. For example, you can easily customize the session id field to meet your needs. You can for example use an auto-incrementation property and let the database system handle it (but keep in mind that once it reaches the maximum it usually makes all INSERT queries to fail, so you have to create a fail-safe mechanism for it - or make the field big enough to meet your needs, although that would be a complete waste of space).

When dealing with storing data, there can be used two approaches (they may be combined though if that suits your need).

- Use a fixed number of variables, each as a column in the session table (I would strongly recommend this).

- Use a method similar to the ones used by the standard library of serializing data and store that in a TEXT field.

The first one has the advantage that it CAN be optimized (it doesn't mean it necesarelly is). For example, you can create all fields CHAR if you have fixed length strings (sometimes you can make the compromise of using a fixed length CHAR field with the size of the longest string accepted instead of using VARCHAR to improve performance). You can also set the INT fields to meet your needs by lowering their size or changing their type - for example, why use a INT(11) for a variable that will only take a yes/no values when you can use a TINYINT(1) or ENUM('y','n')?.

And, of course, with the use of indexes you can improve even more performances according to your needs.

Another nice feature, but also a pain, is the fact that YOU have to handle session basic actions: create and delete the session itself. The creation is pretty straight forward, although it has its own challenges, but in order to delete an expired session can be used two approaches:

- You can check for expired sessions when you create a new session.

- You can create a cron job / scheduled script on the server to check and delete the expired sessions periodically.

- You can combine these two approaches and only check for expired sessions at a specified period when a session is created or accessed (it implies to set a variable to see when was last check and a period after which to check - for both you can use another table in the database, or perhaps plain files - the second one can be directly in the script as well).


Session table example

The end .. for now


I hope you now have a better understanding of sessions and I also hope I've made you consider creating your own session system, or at least using a custom session handling system. In the next articles I will try to explain how to basically create one such system, improve and make everything secure as possible.

 (to be continued)

Related Links:

Creating a customized session handling system in PHP (part II)
Official PHP website
Session handling functions

Posted by: Indy on July 29, 2006 at 08:57.
 

» Comments

Question
How do I store data in $_Session['data']?

Like for example, I am currently creating an online shopping cart, what I want is that, when the moment I click the cart button all possible product information (Like: Product_Id, Product_Name, Product_description) will be store in $_Session['data']. My question is that, How do I store this all information using $_Session?
Is it possible? Please help me.. Thanks !

Posted by Silent_Sinner on October 2, 2010 at 10:57 PM.

Adwords
It is very interesting post to read.I got so many information ,and hope to got so many more information in future.
<a href="http://adhost.dk/kompetencer/adwords">Adwords</a>


Posted by Adwords on September 29, 2012 at 12:03 AM.

Random Article


Search


Feeds


Bubble.ro RSS Feed

All Categories


Articles


Aetolia - The Midnight Age
How to create the histogram of an image using PHP
How to convert an image to grayscale using PHP
How to check if an image is grayscale in PHP
Interchanging 2 variables without the use of a third
Error launching browser window:no XBL binding for browser
Convert the AOL user session collection to a MySQL database
Introduction to Matlab
Creating a customized session handling system in PHP (part II)
Creating a customized session handling system in PHP (part I)
Firefox crashing with Yahoo! Messenger
ADL Search for oDC
Video codecs explained
Browsershots
How to use Auto-Away Message with oDC
Create complete Windows XP disk with SP2 and all updates
Data Execution Prevention error message in Windows XP
Google Mars
Logarithmic scale graphs in Excel
Urban Dictionary (or wtf does l33t mean?)
Learn more about BIOS
Backup your Firefox and Thunderbird settings
Syndicate your Yahoo 360 profile
What is Google PageRank?
'Cannot Open the File: Mk:@MSITStore' Error Message
Get your Gmail with Mozilla Thunderbird
E-Books links
Change the size of your Explorer thumbnails
Remove previews from Windows Explorer
How can I turn off system beeps?
How do I disable Internet Explorer?
What are proxies or how do I protect my anonymity?
How to set aliases triggers or macros in MushClient
What is RSS?
Palm Zire 31 fast review
oDC Installation and Basic Configuration
How I built a 2x80W amplifier (using power modules)
Leech/HotLink Protection
How to block referrer detection?
How to find out your IP address
Getting started with Mushclient
What is spyware and how do I protect my PC from it?
Stumble Upon - random surfing around the web
Automatic file backup for Windows users
How can I read foreign language sites?
Protect your web surfing privacy!
What is BitTorrent?
No more ads! Adblock for Firefox
Why use Firefox instead of Internet Explorer?
How do I create my own Yahoo ID?
© Copyright 2006-2017 Bubble. All rights reserved. Sitemap - Contact