Core PHP

How Sessions Work

A session offers a way to store and access data across multiple pages in a website. Each page that uses sessions must begin with a call to session_start(). The call to session_start() begins or resumes the session so that the session variables may be accessed.

Session data is stored in a file on the server. Each session creates a file in a temporary directory on the server. The location of this of this directory is specified by the setting session.save_path in the php.ini file. On Windows, the temporary will often be C:\Windows\Temp.

php.ini file

When a session is created, three things immediately happen. First, a unique identifier is created by random string of 32 hexadecimal digits; for example, hqf7cnvrmlo864s2mi1pgf46c4 is a string that might be generated. Second, a cookie is generated with the Name and Value pair: PHPSESSID and hqf7cnvrmlo864s2mi1pgf46c4, and this cookie is sent to the client computer where it is stored for future use. Third, a file is created in the designated temporary directory with the named sess_hqf7cnvrmlo864s2mi1pgf46c4.

PHPSESSID Cookie

To begin a session, call session_start() at the very beginning of the PHP file. When session_start() is called, it checks the cookies to see if a session exists. If a session does not exist, one is created. Then the superglobal session array is loaded into memory.

The temporary file directory

The session array is an associative array named $_SESSION[], and each its entries can be accessed at any time during the session. The $_SESSION[] array is loaded from the session file sess_hqf7cnvrmlo864s2mi1pgf46c4 shown below. This particular file only has one entry. The index or name is set as something and its value is a string that is 10 characters long and contains the value some value.

sess_hqf7cnvrmlo864s2mi1pgf46c4 file

This session array can be used to stored any values that the programmer wants persisted across the entire session. The session ends when then user closes the browser or the session times out. When the session ends, all of the session data is deleted. A session can also be ended by the programmer with a call to the session_destroy() function. Also, a single session variable can be deallocated with a call to unset().

As an alternative to calling session_start(), you can set the variable session.auto_start to 1 in the php.ini file to start a session on every page. This may be more convenient, but is less efficient than calling session_start() on the pages where it is needed.

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.