How do PHP sessions work? (not "how are they used?")

In the general situation :

  • the session id is sent to the user when his session is created.
  • it is stored in a cookie (called, by default, PHPSESSID)
  • that cookie is sent by the browser to the server with each request
  • the server (PHP) uses that cookie, containing the session_id, to know which file corresponds to that user.

The data in the sessions files is the content of $_SESSION, serialized (ie, represented as a string -- with a function such as serialize) ; and is un-serialized when the file is loaded by PHP, to populate the $_SESSION array.


Sometimes, the session id is not stored in a cookie, but sent in URLs, too -- but that's quite rare, nowadays.


For more informations, you can take a look at the Session Handling section of the manual, that gives some useful informations.

For instance, there is a page about Passing the Session ID, which explains how the session id is passed from page to page, using a cookie, or in URLs -- and which configuration options affect this.


How Does PHP Session Works

  • Firstly PHP creates a 16-byte long unique identifier number (stored as a string of 32 hexadecimal characters, e.g a86b10aeb5cd56434f8691799b1d9360) for an individual session.

  • PHPSESSID cookie passes that unique identification number to users' browser to save that number.

  • A new file is created on the server with the same name of unique identification number with sess_ prefix (ie sess_a86b10aeb5cd56434f8691799b1d9360.)

  • The browser sends that cookie to the server with each request.

  • If PHP gets that unique identification number from PHPSESSID cookie (on each request), then PHP searches in the temporary directory and compares that number to the file name. If both are the same, then it retrieves the existing session, otherwise it creates a new session for that user.

A session gets destroyed when the user closes the browser or leaves the site. The server also terminates the session after the predetermined period of session time expires. These are the simple mechanism steps that PHP is using to handle the session. I hope this article with help you to understand how PHP SESSION is working.

Tags:

Php

Session