Understanding and Example of PHP SESSION Mechanism

  • 2021-12-04 18:22:45
  • OfStack

There are two ways to save PHP SESSION, session.save_handler = files And session.save_handler = user Which way to save can be realized by configuring php. ini file.

1. Save SESSION data by reading and writing files (session.save_handler = files)

1. session_start ()

(1). session_start() Is the beginning of session mechanism, it has a certain probability to start garbage collection, because session is stored in a file, PHP's own garbage collection is invalid, SESSION's collection is to delete files, this probability is based on php. ini configuration decision, but some systems are session.gc_probability = 0 That is, the probability is 0, but garbage collection is implemented through the cron script.


session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440// Expired time   Default 24 Minutes 
// The probability is  session.gc_probability/session.gc_divisor  Results  1/1000, 
// It is not recommended to set it too small because session You need to check whether each file is out of date. 
session.save_path = // It seems that different systems do not default 1 Sample, have 1 The settings are  "N;/path"
// This is random hierarchical storage. In this case, garbage collection will not work, so you need to write your own script 

(2). session will determine whether there is a $_COOKIE[session_name()];session_name() Returns the COOKIE key value holding session_id, which can be found from php. ini


session.name = PHPSESSID // Default value PHPSESSID

(3). 1 session_id is generated if it does not exist, and then the generated session_id is passed to the client as the value of COOKIE.

It is equivalent to performing the following COOKIE operation. Note that this step performs setcookie () operation, COOKIE is sent in header header, which can't have output before, and PHP has another function session_regenerate_id (), which can't have output before if you use this function.


setcookie(session_name(),
  session_id(),
  session.cookie_lifetime,// Default 0
  session.cookie_path,// Default '/' Valid in current program and directory 
  session.cookie_domain,// Default to null 
  )

(4). If it exists then session_id = $_COOKIE[session_name]; Then go to the folder specified by session.save_path to find the name 'SESS_' . session_id() Documents of; Read the contents of the file, deserialize it, and put it in $_ SESSION.

2. Assign a value to $_ SESSION

For example, add a new value $_SESSION['test'] = 'blah'; Then the $_ SESSION will only be maintained in memory. When the script is finished, write the value of $_ SESSION to the folder specified by session_id, and then close the related resources.

At this stage, it is possible to perform the operation of changing session_id, such as destroying an old session_id, generating a brand-new session_id, and half of it is used to customize session operation and role conversion. For example, the anonymous user of Drupal. Drupal has an SESSION, which needs to be replaced with a new session_id after logging in.


if (isset($_COOKIE[session_name()])) {
 setcookie(session_name(), '', time() - 42000, '/');// Old session cookie Expired 
}
session_regenerate_id();// This 1 Step generates a new session_id
//session_id() Returns a new value 

3. Write SESSION operation

At the end of the script, an SESSION write is performed to write the value in $_SESSION to the file named session_id, which may already exist and may require the creation of a new file.

4. Destroy SESSION

SESSION sent out of the COOKIE1 like real-time COOKIE, stored in memory, when the browser closed, will expire, if the need for artificial forced expiration, such as login exit, rather than close the browser, then need to destroy SESSION in the code, there are many methods

setcookie (session_name (), session_id (), time ()-8000000,...); //Execute before logging out usset ($_ SESSION); //This deletes all $_ SESSION data, and when refreshed, COOKIE comes in, but no data. session_destroy (); //This is more thorough, deleting $_SESSION deleting the session file, and session_id

When the browser is not closed, refresh again, the latter two will have COOKIE, but no data can be found

2. Customize the session processing mechanism (session.save_handler = user)

User-defined session processing mechanism, more intuitive


* session_set_save_handler('open', 'close', 'read', 'write', 'destroy', 'gc'); 

1. session_start ()

Execute open($save_path, $session_name) Open the session operation handle; $save_path This is session.save_path in the case of session.save_handler = files, but if user-defined, neither parameter is needed and TRUE is returned directly

Execute read ($id) to read data from it; This parameter is passed automatically, that is, session_id (), and can be manipulated by this value.

2. End of script execution

Execute


write($id, $sess_data) // Two parameters, very simple 

3. If the user needs session_destroy ()

Execute destroy first. After executing step 2,

1 practical example:


//SESSION Called when initializing 
function open($save_path, $session_name)
{
 global $sess_save_path;
 $sess_save_path = $save_path;
 return(true);
}
// Called when closed 
function close()
{
 return(true);
}
function read($id)
{
 global $sess_save_path;
 $sess_file = "$sess_save_path/sess_$id";
 return (string) @file_get_contents($sess_file);
}
// Before the script execution ends, perform the write operation 
function write($id, $sess_data)
{
 echo "sdfsf";
 global $sess_save_path;
 $sess_file = "$sess_save_path/sess_$id";
 if ($fp = @fopen($sess_file, "w")) {
 $return = fwrite($fp, $sess_data);
 fclose($fp);
 return $return;
 } else {
 return(false);
 }
}
function destroy($id)
{
 global $sess_save_path;
 $sess_file = "$sess_save_path/sess_$id";
 return(@unlink($sess_file));
}
function gc($maxlifetime)
{
 global $sess_save_path;
 foreach (glob("$sess_save_path/sess_*") as $filename) {
 if (filemtime($filename) + $maxlifetime < time()) {
  @unlink($filename);
 }
 }
 return true;
}

Complementarity-involving functions


session_start() ; //  Open session Answer, in which session_id() The value of is 1 Flags for sub-independent sessions 
session_name(); //  The default is PHPSESSID, In php.ini You can configure yourself in the file. 
session_id(); //  In cookie Is embodied in, session_name Is the key, session_id Is the value 
setcookie(); //  To remember the effect, there must be a refresh of the page 
session_destory(); // session_destroy  -   Destruction 1 All data in a session 

Summarize


Related articles: