Skip to content
Advertisement

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

Session files are usually stored in, say, /tmp/ on the server, and named sess_{session_id}. I have been looking at the contents and cannot figure out how they really work.

Fetching the variable name and and content from the file is easy. But how does PHP know what session belongs to whom?

The session_id seems totally random and one IP address can have several users, and each user can have several sessions if they have more than one browser window open.

So how does it work?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement