21 May 06
Beginner PHP Tutorial 9: Sessions
While coding your php applications I guarantee that eventually you will need to create a system that deals with users logging in and out. The problem is that when the logged in user moves from page to page the system must “recognise” the user and save all their details across each access. The second part is quite simple, you just store the data somewhere in relation to their username or user id (don’t worry if you don’t understand this). The first part, however, is a problematic process. There are a few very easy to implement solutions, but these can be very insecure. Let’s assume that our test application checks the users username and password every time they access a page. That’s easy, but where does the username and password come from? The first answer, and the wrong answer is that they come from the user. I’ll show you why it’s wrong…here are some immediate and insecure solutions:
- Use the GET method by placing the username and password in the url. This would probably mean that all urls in the user area contain an extra ”?username=USER&password=PASS” on the end, so that other pages recognise the user. The problem with this method is any user can see the username and password directly in their address bar. However, if you encrypt the data you can stop this happening. Technical experts will realise however, that all they need to do is send the encrypted data and your application will decrypt it and accept the user. Having such important information in the url is a definite no no.
- Use the POST method by placing the username and password in a form. This is similar to using GET, except all the data is transferred through forms as POST data and is therefore not visible in the url, but still can be used to identify the user. The downsides of this method is that A) any technical expert can read the source and find the form so it’s not much better than GET and B) you have to have submit buttons all over the place to keep the user logged in. The GET and POST methods also bring the problem that a user may access a page not linked to such as the home page by typing it and the application would then not recognise them.
- Use a cookie – A cookie is a browser feature that allows web applications to store and retrieve small amounts of data on the client’s computer. This means that an application can identify a user by simply taking a look at the cookie area allocated to the website to see if there are any user details, and if so, checking them. This is a lot better, but still has its flaws. Firstly, it is possible to read from cookies using XSS (cross-site scripting), which is a common vulnerability in web applications that allows a user to insert code into the application (usually javascript). Secondly, and probably more importantly, some users set their browsers to not accept cookies as they believe it is a security issue or they just don’t want data from other sites on their computer. This decision should be respected so the application should work with cookies enabled and disabled.
As you can see all 3 of the methods have problems. Now let me explain where the data comes from when dealing with sessions and why. To answer the question the username and password come from the server (a file on the website). What? How does the data get there? Now we’re in to the realm of sessions. Well, when the user first logs in the application they are set a random id (called a Session ID) full of letters, numbers and whatever else.
A problem which is shared across the methods mentioned above is that they openly transfer sensitive data. A session ID is a way to stop this, by only transferring a meaningless ID, which can easily change during and between requests. In php sessions all the data is stored in files and the Session ID is used to figure out what data belongs to who. Also, when they first log in their username and password is saved in the session file next to the Session ID. The system then combines all of the three methods mentioned above, first attempting to store the Session ID via a cookie but otherwise storing the Session ID in the url (using the GET method) or in a form with a hidden field (using the POST method) if the browser does not support cookies or the user has disabled them.
Now, when the user next accesses a page the Session ID is used to retrieve the data from the file. If the user logs out or the pages are not accessed with the Session ID for a short duration (usually anywhere from 5 minutes to an hour, depending on the security level required by the application), it is destroyed, including all the data it refers to. This means a new Session ID is created when the user logs in again, creating a reasonably secure method to transfer data across pages. Well, now we’ve pretty much done the theory of how it works, let’s start writing some php.
session_start();
This function initialises the session, looking for a session id. If it can’t find one then it creates a new one and creates a new blank area for session data. Otherwise it will find and obtain the saved session data ready for you to access.
$_SESSION
This array contains all the session data. So in a new session this is just a blank array but it can hold data from previous accesses. Here is an example:
session_start();
if(!isset($_SESSION['data'])){
echo 'No Data';
}else{
echo $_SESSION['data'];
}
$_SESSION['data'] = 'This is saved in the session';
Assuming all goes well when you access it first time it will say “No Data” but subsequent accesses will say “This is saved in the session”. There is only one final element that you will probably need:
session_destroy();
This function simply destroys all the data with a session and would be probably be used if the user “logged out”.
Well to be honest, that’s all you really need to know about sessions. If you want to know more about the functions then you can go to the PHP Manual and check out the stuff there. This will help you if you want to add extra security to your application or if you wish to store session data in a database rather than a file. Your new knowledge should make everything you read there much easier to understand.
Now you have read through this tutorial write some php scripts just to get used to using sessions. After a while it’ll just be a doddle!


Very clear tutorial, although you could explain how the cookie or get method keeps the session id data e.t.c abit more, as I don’t understand it :)
I’ve updated the tutorial to try to provide a better explanation of how the session data is held between requests. I hope this helps you and I’m very grateful for your comments and constructive criticism.
what is PHP’s code for session identifier for the currently logged in user in a website that requires log-in? In ColdFusion is typically is #request.memberid# or something similar.
If I’m understanding you correctly, you can use the session_id() function to get the current session identifier.