Skip to main content

Getting started with PHP sessions

HTTP is a stateless protocol. That is, a HTTP request to a website has no information or record of the preceding requests. This is where sessions come into picture. Sessions is a mechanism to preserve data across subsequent accesses. Using sessions, a website is able to maintain state, that is, remember which requests they received previously. Without sessions, websites would have not have progressed beyond simple static HTML pages.

Starting a session in PHP is as simple as adding the following code to a PHP script: session-test.php

A closer look at session_start

When the browser calls the session-test.php page, the following two actions take place:

1. Send cookie headers PHP sends back a set cookie header in its response to the above request. The headers might look something like these:

The first header tells the browser to create cookie named PHPSESSID1 and set its value to a11a3e23048a0372341ca3dfb24171002.

The second header tells the browser to set the expiry time of the cookie to “Thu, 19 Nov 1981 08:52:00 GMT“. Please note that date is in the past, which essentially means that browser should discard the cookie as soon the browser window is closed. This is what is referred to as a temporary cookie.

You can control session/cookie name by using session_name. Similarly you can control the cookie’s expiry time by settings its value using:

2. Create file to store session data After sending the cookie headers, PHP creates a file on the server to store the session data in the session save directory. Whatever you save in the session is written to this file. You may also use database to hold the session data but we will discuss that later. The file may be named something as sess_a11a3e23048a0372341ca3dfb2417100. The directory where the above file is created can be controlled by either calling session_save_path or by setting the value of session.save_path in php.ini file.

Ok, now I have created a session. How do I use it?

When a session is started, an associative array named $_SESSION is made available to the script. You can use this array as you would use any other associative array.

get-session.php

Remember to start the session before accessing the $_SESSION array. This array is made available after you have started the session.

1 Cookie/Session Name

2 Random 32-character alphanumeric hash generated by PHP

One thought on “Getting started with PHP sessions

  1. Thanks for the article. It’s good for getting a quick overview on the very basics and understanding what’s going on “behind the scenes”.

Leave a Reply

Your email address will not be published. Required fields are marked *

*