Latest Posts

Thursday, February 23, 2017

How sessions work in PHP

Recently I was helping one of my client in hiring PHP developer . I was surprise to know that 80 % of candidate don't know about how PHP session works.

People were aware about the functions like session_start , $_SESSION etc but not  aware about how it works over the HTTP. Most of the candidate stuck when they were told that HTTP is connection less protocol and on every request a new connection is created . 

https://www.tutorialspoint.com/php/php_sessions.htm

In PHP Session management is a way to make data accessible across the various pages.

A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.
The location of the temporary file is determined by a setting in the php.ini file called session.save_path. Before using any session variable make sure you have setup this path.
When a session is started following things happen −
  • PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
  • A cookie called PHPSESSID is automatically sent to the user's computer to store unique session identification string.
  • A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443.
When a PHP script wants to retrieve the value from a session variable, PHP automatically gets the unique session identifier string from the PHPSESSID cookie and then looks in its temporary directory for the file bearing that name and a validation can be done by comparing both values.
A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.

Starting a PHP Session

A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.


Changing the name of PHPSESSID 

We can change the name by calling session_name before any call to session_start or session_register .

session_name('mySessionName');
session_start();

 Other method is to set the name in php.ini . The variable session.name specifies the name of the session which is used as cookie name. It should only contain alphanumeric characters. Defaults to PHPSESSID

For further reference please visit to below link

http://se.php.net/manual/en/session.configuration.php#ini.session.name
 

No comments:

Post a Comment