Zum Hauptinhalt springen

Session Management

What happens in the system when session_start() is called?​

When session_start() is called, PHP checks if the client (browser) sent a session ID via a cookie — usually named PHPSESSID.

Example: PHPSESSID=abc123xyz456

If the cookie exists, PHP uses the session ID from the cookie and tries to find a session file on the server that matches this ID (in tmp folder).

If no cookie is sent (new visitor or expired session), PHP generates a new session ID and prepares to create a new session file.

(2) PHP reads or creates a new session file​

PHP looks for a session, file typically stored in a folder like /tmp, /var/lib/php/sessions, or as defined in php.ini (session.save_path).

Session files are usually named like: sess_e6uoembqkeqn6ekfelr52p5spl

If the file exists, PHP reads and deserializes it into the global $_SESSION array.

Example of a session string:

user_session_id|i:1;user_session_email|s:20:"michael@schneider.de";user_session_name|s:7:"Michael";

If it doesn’t exist, PHP initializes an empty $_SESSION array.

(3) PHP populates $_SESSION Superglobal​

PHP populates the $_SESSION array with the key-value pairs stored in the session file.

Example:

$_SESSION = [
'user_session_id' => 5,
'username' => 'alice'
];

(4) PHP locks the Session File​

To prevent race conditions, PHP locks the session file while the script is running Other requests using the same session ID have to wait until the session is closed (session_write_close() or script end).

(5) Registers Session to be Saved at the End​

At the end of the script (or when session_write_close() is called), PHP:

  1. Serializes the $_SESSION array (turns it into a storable string format).
  2. Writes that string to a session file on the server. Example file: /var/lib/php/sessions/sess_e6uoembqkeqn6ekfelr52p5spl
$_SESSION['theme'] = 'dark';

String in the session file will look like this:

theme|s:4:"dark";

PHP Releases the file lock, so other requests can use the session.