English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Explanation of Session Function in ThinkPHP

In PHP, $_SESSION is used to operate session, and ThinkPHP provides the encapsulation function session(). This single function implements the functions of adding, deleting, modifying, and querying session. Below, we will look at its application and implementation separately.

The definition of the session() function is in Common/defined in functions.php.

session configuration

The session($name='',$value='') function has two parameters. When $name is an array, it is used to set the session. Usage is as follows:

$name = array(
     'name' => 'name'
     'path' => ''/tmp/
     'expire' => 0
);
session($name);

These are settings made before enabling session. When defining the function in ThinkPHP, it first checks if $name is an array. If it is an array, it means that the session is being set, and then the corresponding code is executed to set it.

The implementation code is as follows:

if (is_array($name)) { // session initialization, called before session_start
  if (isset($name['prefix'])) C('SESSION_PREFIX', $name['prefix']);
  if (C('VAR_SESSION_ID') && isset($_REQUEST[C('VAR_SESSION_ID')])) {
    session_id($_REQUEST[C('VAR_SESSION_ID')]);
  } elseif (isset($name['id'])) {
    session_id($name['id']);
  }
  if ('common' != APP_MODE) { // Other modes may not be supported.
    ini_set('session.auto_start', 0);
  }
  if (isset($name['name'])) session_name($name['name']);
  if (isset($name['path'])) session_save_path($name['path']);
  if (isset($name['domain'])) ini_set('session.cookie_domain', $name['domain']);
  if(isset($name['expire'])) {}}
    ini_set('session.gc_maxlifetime',  $name['expire']);
    ini_set('session.cookie_lifetime', $name['expire']);
  }
  if(isset($name['use_trans_sid'])) ini_set('session.use_trans_sid', $name['use_trans_sid']&63;1:0);
  if(isset($name['use_cookies'])) ini_set('session.use_cookies', $name['use_cookies']&63;1:0);
  if(isset($name['cache_limiter'])) session_cache_limiter($name['cache_limiter']);
  if(isset($name['cache_expire'])) session_cache_expire($name['cache_expire']);
  if(isset($name['type']))  C('SESSION_TYPE', $name['type']);
  ……
}

In ThinkPHP, the storage system for sessions provides two database options: mysql and memcache. Of course, by default, it uses file storage. The code to determine the session storage method is as follows:

if(C('SESSION_TYPE')) { // Read session driver
  $type = C('SESSION_TYPE');
  //System calls the mysql driver program
$class = strpos($type,'\\')?63; $type : 'Think\\Session\\Driver\\'. ucwords(strtolower($type));
$hander =  new $class(); //Instance the handler
//Register the handler
  session_set_save_handler( 
    array(&$hander, "open"),
    array(&$hander, "close"),
    array(&$hander, "read"),
    array(&$hander, "write"),
    array(&$hander,"destroy"),
    array(&$hander,"gc")
  );
}

The configuration of the session storage system is set through the configuration option SESSION_TYPE.

SESSION_TYPE=>'Mysql'  //Store session in mysql database

After the setting is completed, if session auto-start is set, the system will automatically start the session

// Start session
if(C('SESSION_AUTO_START')) session_start();

If you want to turn off the session auto-start, set the option SESSION_AUTO_START as follows:

SESSION_AUTO_START => false

If the system auto-start is turned off, you can manually start the session in the public file of the project or in the controller by calling session_start() manually. Or use the function session(), whose starting method is as follows:

session(''[start]'');

The implementation code in ThinkPHP is as follows:

if('[pause]'==$name){ // Pause session
   session_write_close();
}elseif('[start]'==$name){ // Start session
   session_start();
}elseif('[destroy]'==$name){ // Destroy session
   $_SESSION = array();
   session_unset();
   session_destroy();
}elseif('[regenerate]'==$name){ // Regenerate id
   session_regenerate_id();
}

Session assignment

Session assignment is relatively simple, use it directly:

session('name','onmpw');

In addition, the key-value can also be multi-layered with '.' as the connection.

session(‘name1.name2','onmpw');  //is equivalent to $_SESSION[‘name1'][‘name2'] = 'onmpw';

The implementation code for session assignment in ThinkPHP is as follows:

if(strpos($name,'.')){
     list($name1,$name2) = explode('.',$name);
     if($prefix){
          $_SESSION[$prefix][$name1[$name2] = $value;
     }else{
          $_SESSION[$name1[$name2] = $value;
     }
}else{
     if($prefix){
          $_SESSION[$prefix][$name] = $value;
     }else{
          $_SESSION[$name] = $value;
     }
}

The $prefix is configured through the option SESSION_PREFIX.

Session value retrieval

Retrieving session values is relatively simple.

Firstly, let's get all sessions, the usage is as follows

$values = session();

At this point, the result is an array. The implementation code in ThinkPHP is as follows:

if(''===$name){
  // Get all sessions
  return $prefix ? $_SESSION[$prefix] : $_SESSION;
}

Then it is to retrieve a single value

$value1 = session('name');
//or
$value2 = session('name1.name2');

The implementation code is as follows:

if(strpos($name,'.')){
   list($name1,$name2) = explode('.',$name);
   return isset($_SESSION[$name1[$name2])?$_SESSION[$name1[$name2:null; 
}else{
   return isset($_SESSION[$name])?$_SESSION[$name]:null;
}

Session deletion

The deletion of session is divided into clearing session, destroying session, and deleting a single session value.

First, let's talk about clearing session. Clearing session passes the parameter value of null to $name

session(null); //Clear session

The implementation code is as follows:

if(is_null($name)){ // Clear session
   if($prefix) {
    unset($_SESSION[$prefix]);
   }else{
    $_SESSION = array();
   }
}

Clearing session simply clears the data corresponding to session in the file or table, but the file will still exist.

Destroy session

session('[destroy]');

The implementation code in ThinkPHP is as follows:

if('[destroy]'==$name){ // Destroy session
   $_SESSION = array();
   session_unset();
   session_destroy();
}

The difference between destroying session and clearing session is that destroying session will also destroy the file.

Finally, it is the deletion of a single session value. The usage is as follows

session('name', null);

Delete a single session value, setting the second parameter $value to null will delete it.

if(is_null($value)){ // Delete session
  if(strpos($name,'.')){
    list($name1,$name2) = explode('.',$name);
    if($prefix){
      unset($_SESSION[$prefix][$name])1[$name2]);
    }else{
      unset($_SESSION[$name])1[$name2]);
    }
   }else{
    if($prefix){
      unset($_SESSION[$prefix][$name]);
    }else{
      unset($_SESSION[$name]);
    }
  }
}

Check session

Finally, a brief introduction to the check of session. Checking means whether a variable exists. The original PHP check session variable is as follows

isset($_SESSION['name']);

The way the session() function is used after ThinkPHP encapsulation is to check

session('?name'); //Determine if a session has been set

Its code implementation also uses the original check method

$name = substr($name,1);
if(strpos($name,'.')){ // Support arrays
   list($name1,$name2) = explode('.',$name);
   return $prefix?isset($_SESSION[$prefix][$name1[$name2]:isset($_SESSION[$name1[$name2]);
}else{
   return $prefix?isset($_SESSION[$prefix][$name]):isset($_SESSION[$name]);
}

The above is almost an introduction to the various functions of the session() function, as well as how ThinkPHP implements it. I hope the content of this article can help everyone in using ThinkPHP.

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, does not edit the content manually, and does not assume relevant legal liabilities. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (When reporting via email, please replace # with @) for reporting violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.

You May Also Like