php session

Have you ever wondered what is happening internally when you use PHP session? Or how and where data are kept when navigating through different pages?

In this article you will learn how PHP manages sessions and what is happening behind the scenes.

But first, what is PHP session?

PHP session is a way to persist data across subsequent accesses and/or multiple pages. Differently from cookies, session data are stored in the server and can’t be directly manipulated by the user.

Its basic usage is quite simple: you just have to start a session and then you can store data in it and retrieve them later. Here is an example:

<?php
// start the session
session_start();

// "first_access" is empty only in the very first access
if(empty($_SESSION["first_access"])){
	$_SESSION["first_access"] = Date("Y-d-m H:i:s");
}

// everytime the page is accessed it will show the date/time of the first access
echo "Your very first access was in " . $_SESSION["first_access"];


Session management - behind the scenes

Basically, the default PHP session management process can be divided into three parts: starting the session, storing data and closing the session.

Here is what happens in the very first time an user access our example above, which uses session:

1) Starting the session

2) Storing information

3) Closing the session

For subsequent accesses, there is a difference in how session is started:

Custom session management

The default session management is by far the most commonly used one, which is file system as explained above: data are stored in and retrieved from a file in the disk. But in certain cases you may prefer to use custom session handlers (e.g., database), which can be done through the session_set_save_handler function; but be aware that you would have to create all the basic operations used in session management: open/start, close, read, write, destroy, and also garbage collect.

You can find more information and some examples in the session_set_save_handler documentation.