Tutorials

Sessions and cookies: Adding state to a stateless protocol

by Daniel Egeberg on Jun 5, 2008 6:45:45 AM

Sessions

Another popular method is using sessions. Sessions are very similar to cookies, but they are distinctive in a few important ways. While cookies are stored on the client machine, sessions are stored on the server.

The way sessions work are by generating a random ID for the user. This ID is stored in a cookie on the client machine. PHP will then fetch all session data related to that ID from wherever it is stored. By default it's stored on the harddisk, but it's possible to write your own save handler so you can store it in e.g. a database. By default, the cookie will be called PHPSESSID and will expire when the browser is closed.

Seeing as you are using a cookie for identifying the user you'll need a way to set the same settings for the cookie as we did before. For this purpose you can use the session_set_cookie_params() function. It has the following syntax:

session_set_cookie_params(int $lifetime[, string $path[, string $domain[, bool $secure[, bool $httponly]]]])

Using session data

Before you are able to use sessions you'll have to call session_start(). This function will, like when setting cookies, have to be called before any output has been sent to the browser. Once this has been done, storing data in sessions and retrieving the values is quite easy:

Like $_COOKIE, $_SESSION is a super-global as well.

An example of using sessions

This is how the script we made using cookies on the previous page will look if we decide to use sessions instead:

Sessions without cookies

Sessions do not always have to use cookies. Whatever value you choose for the session name (PHPSESSID by default) just have to be present somewhere. It could for instance be through the URL like this: http://example.com/index.php?PHPSESSID=jfJk87Hfja87Hajhsd97Hash or it could be through a form field (either via POST or GET). The manual has more information about this, but I would recommend you just use the cookies.

On the next page we will talk a bit about security...

Comments

Thanks, this tutorial helped me out.

1. GreenUser on Aug 15, 2008 3:24:45 PM

Good tutorial, it helped me out as well. :)

2. BuzzardB on Oct 2, 2008 5:47:49 PM

i want to store cookie value in database and fetch that value and save it as session so whenever i delete cookies of browser i should retrive same state before deleting cookies
i am doing for portal of extjs and want this code in php

3. rohan354 on Oct 10, 2008 5:54:14 AM
Login or register to post a comment.