Understanding Sessions

Originally, a session is a visit of a user to a website. He clicks on a few links, has a look at a couple of pages, and then leaves. This defines a session. Or, to put it in other words: If a user does not request any data from a website for a period of time, for example 20 minutes, the session ends.

HTTP does not know any kind of session mechanism; the protocol is stateless. However, PHP comes with a built-in session support that makes it fairly easy to use sessions.

After a session is created, PHP generates a session ID, that is, a long string that identifies the session. PHP then creates a file or a database entry for this session. Then, the PHP application can store data in this session. This data is then written either into the session file or into the database (shared memory is another, but rarely used option).

So, the only thing that must be transported between the client and the server is the session ID. All other data relevant to the session resides at the server. So, no sensitive data is sent over the wire an unnecessary amount of times.

The configuration of PHP's session mechanism is completely triggered in the [session] section of the php.ini configuration file. The default settings might not be suitable for all applications, so the next few code cover some possible configurations.

Where to Store the Sessions

Usually, session data is stored in files. The location of these files is set in the php.ini directive session.save_path. Of course, this path must (a) exist and (b) be readable and writable for the PHP process (usually, the process of the web server). Otherwise, the session information cannot be stored.

However, when you have a lot of users and, therefore, a lot of sessions, PHP should not put all session files in one directory because this might cause some serious performance issues. The following syntax allows PHP to move session data into many subdirectories:

session.save_path = "n;/tmp"

This creates subdirectories up to the level of n within the /tmp directory. However, these subdirectories have to exist so that PHP's session mechanism can write into them; for this, there exists the shell script in the ext/session directory.

Of course, only the web server should be allowed to read this directory; otherwise, other users in the system could be able to read session information with possibly sensitive data.