Categories
PHP Tips and Tricks

How Does PHP Session Works

Basically, the session is the system or way to store information for individual users. It’s storing individual users information against a unique session ID. So in this way, user’s data can be accessible across all pages of a website. PHP follow simple workflow for manage session, and that is when a session is started, then PHP either retrieve existing session or create a new session. If PHPSESSID is passed then PHP retrieved existing session otherwise creates a new session

By default, session creates a file in a temporary directory (which determined in php.ini file) on a server. All all the variables & value are stored there.

How Does PHP Session Works

How is Works:

  • Firstly PHP creates a unique identifier number (a random string of 32 hexadecimal number, e.g 3c7foj34c3jj973hjkop2fc937e3443) 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_3c7foj34c3jj973hjkop2fc937e3443.)
  • 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.

By Sohel Rana

PHP Programmer, Software Engineer & Technology lover

Leave a Reply

Your email address will not be published. Required fields are marked *