search
HomeBackend DevelopmentPHP TutorialHow to use the session function in ThinkPHP

How to use the session function in ThinkPHP

Jun 09, 2018 am 10:03 AM
sessionthinkphpfunction

这篇文章主要为大家详细介绍了ThinkPHP中session函数,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

在PHP中使用$_SESSION来操作session,而ThinkPHP提供了session的封装函数session()。单单这一个函数就实现了session的增删改查的功能。下面我们分别来看其应用与实现。

该session()函数的定义是在Common/functions.php中定义。

session配置

session($name='',$value='')函数有两个参数,$name为数组的时候是对session进行设置。使用如下:

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

这些是在开启session之前进行设置的。在ThinkPHP中定义该函数的时候是先判断$name是否为数组,如果为数组的话就说明是在对session进行设置,然后进入相应的代码执行设置。

其实现代码如下:

if(is_array($name)) { // session初始化 在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){ // 其它模式可能不支持
    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']?1:0);
  if(isset($name['use_cookies'])) ini_set('session.use_cookies', $name['use_cookies']?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']);
  ……
}

在ThinkPHP中,对于session的存储系统提供了mysql和memache两种数据库。当然默认情况下是使用文件存储。判断session存储方式的代码如下:

if(C('SESSION_TYPE')) { // 读取session驱动
  $type = C('SESSION_TYPE');
  //系统调用mysql驱动程序
$class = strpos($type,'\\')? $type : 'Think\\Session\\Driver\\'. ucwords(strtolower($type));
$hander =  new $class(); //实例化处理器
//注册处理器
  session_set_save_handler( 
    array(&$hander,"open"),
    array(&$hander,"close"),
    array(&$hander,"read"),
    array(&$hander,"write"),
    array(&$hander,"destroy"),
    array(&$hander,"gc")
  );
}

对于session存储系统的配置是通过配置选项SESSION_TYPE来设置的。

SESSION_TYPE=>'Mysql'  //将session存储在mysql数据库中

设置完成以后如果设置了session自动启动,那系统会自动开启session

// 启动session
if(C('SESSION_AUTO_START')) session_start();

如果想关闭session自启动,对选项SESSION_AUTO_START设置如下:

SESSION_AUTO_START => false

如果关闭了系统自启动,可以在项目的公共文件或者在控制器中通过手动调用session_start()来开启session。或者使用函数session(),其开启方法如下:

session(‘[start]');

在ThinkPHP中其实现代码如下:

if('[pause]'==$name){ // 暂停session
   session_write_close();
}elseif('[start]'==$name){ // 启动session
   session_start();
}elseif('[destroy]'==$name){ // 销毁session
   $_SESSION = array();
   session_unset();
   session_destroy();
}elseif('[regenerate]'==$name){ // 重新生成id
   session_regenerate_id();
}

session赋值

session赋值比较简单,直接使用:

session('name','onmpw');

除此之外对于键值还可以是多层的中间使用‘.'连接。

session(‘name1.name2','onmpw');  //等价于 $_SESSION[‘name1'][‘name2'] = ‘onmpw';

在ThinkPHP中对于session赋值的实现代码如下:

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;
     }
}

$prefix是通过选项SESSION_PREFIX来配置的。

session取值

session取值相对来说也是比较简单的。

首先是获取全部的session,使用方法如下

$values = session();

此时得到的是一个数组。在ThinkPHP中实现代码如下:

if(''===$name){
  // 获取全部的session
  return $prefix ? $_SESSION[$prefix] : $_SESSION;
}

再就是取出单个值

$value1 = session(‘name');
//或者
$value2 = session(‘name1.name2');

其实现代码如下:

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删除

session的删除分为清空session,销毁session和删除单个session值。

先说清空session。清空session传参给$name的值为null

session(null); //清空session

其实现代码如下:

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

清空session只是将session对应的文件或者表中的数据清除,但是文件还是会存在的。

销毁session

session(‘[destroy]');

其ThinkPHP中的实现代码如下:

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

销毁session和清空session不同的是销毁session会将文件一并销毁。

最后就是删除单个session值。使用方式如下

session(‘name',null);

删除单个session值,将第二个参数$value的值设为null即可删除。

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

检查session

最后简单介绍对session的检查。检查是指一个变量是否存在。原生的PHP检查session变量是这样检查的

isset($_SESSION[‘name']);

ThinkPHP封装之后使用session()函数是这样检查

session(‘?name'); //判断一个session是否已经设置

其代码实现也是利用了原生的检查的方式

$name  = substr($name,1);
if(strpos($name,'.')){ // 支持数组
   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]);
}

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

php中session与thinkphp中session的一些用法

The above is the detailed content of How to use the session function in ThinkPHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to calculate the total number of elements in a PHP multidimensional array?How to calculate the total number of elements in a PHP multidimensional array?May 15, 2025 pm 09:00 PM

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

What are the characteristics of do-while loops in PHP?What are the characteristics of do-while loops in PHP?May 15, 2025 pm 08:57 PM

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

How to hash strings in PHP?How to hash strings in PHP?May 15, 2025 pm 08:54 PM

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.

How to implement array sliding window in PHP?How to implement array sliding window in PHP?May 15, 2025 pm 08:51 PM

Implementing an array sliding window in PHP can be done by functions slideWindow and slideWindowAverage. 1. Use the slideWindow function to split an array into a fixed-size subarray. 2. Use the slideWindowAverage function to calculate the average value in each window. 3. For real-time data streams, asynchronous processing and outlier detection can be used using ReactPHP.

How to use the __clone method in PHP?How to use the __clone method in PHP?May 15, 2025 pm 08:48 PM

The __clone method in PHP is used to perform custom operations when object cloning. When cloning an object using the clone keyword, if the object has a __clone method, the method will be automatically called, allowing customized processing during the cloning process, such as resetting the reference type attribute to ensure the independence of the cloned object.

How to use goto statements in PHP?How to use goto statements in PHP?May 15, 2025 pm 08:45 PM

In PHP, goto statements are used to unconditionally jump to specific tags in the program. 1) It can simplify the processing of complex nested loops or conditional statements, but 2) Using goto may make the code difficult to understand and maintain, and 3) It is recommended to give priority to the use of structured control statements. Overall, goto should be used with caution and best practices are followed to ensure the readability and maintainability of the code.

How to implement data statistics in PHP?How to implement data statistics in PHP?May 15, 2025 pm 08:42 PM

In PHP, data statistics can be achieved by using built-in functions, custom functions, and third-party libraries. 1) Use built-in functions such as array_sum() and count() to perform basic statistics. 2) Write custom functions to calculate complex statistics such as medians. 3) Use the PHP-ML library to perform advanced statistical analysis. Through these methods, data statistics can be performed efficiently.

How to use anonymous functions in PHP?How to use anonymous functions in PHP?May 15, 2025 pm 08:39 PM

Yes, anonymous functions in PHP refer to functions without names. They can be passed as parameters to other functions and as return values ​​of functions, making the code more flexible and efficient. When using anonymous functions, you need to pay attention to scope and performance issues.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.