Home php教程 PHP开发 Detailed explanation of session function in ThinkPHP

Detailed explanation of session function in ThinkPHP

Dec 22, 2016 am 10:11 AM
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);
Copy after login

这些是在开启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']);
  ……
}
Copy after login

在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")
  );
}
Copy after login

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

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

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

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

如果想关闭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();
}
Copy after login

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;
     }
}
Copy after login

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

session取值

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

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

$values = session();

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

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

再就是取出单个值

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

其实现代码如下:

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;
}
Copy after login

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();
   }
}
Copy after login

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

销毁session

session(‘[destroy]');

其ThinkPHP中的实现代码如下:

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

销毁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]);
    }
  }
}
Copy after login

检查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]);
}
Copy after login

   

以上几乎是对session()函数各个功能的使用介绍,以及ThinkPHP是如何实现的。希望本文的内容对大家在使用ThinkPHP过程中起到一些帮助作用。

更ThinkPHP中session函数详解相关文章请关注PHP中文网!

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
24
How to set session timeout in SpringBoot Session How to set session timeout in SpringBoot Session May 15, 2023 pm 02:37 PM

The problem was found in the springboot project production session-out timeout. The problem is described below: In the test environment, the session-out was configured by changing the application.yaml. After setting different times to verify that the session-out configuration took effect, the expiration time was directly set to 8 hours for release. Arrived in production environment. However, I received feedback from customers at noon that the project expiration time was set to be short. If no operation is performed for half an hour, the session will expire and require repeated logins. Solve the problem of handling the development environment: the springboot project has built-in Tomcat, so the session-out configured in application.yaml in the project is effective. Production environment: Production environment release is

What should I do if the php session disappears after refreshing? What should I do if the php session disappears after refreshing? Jan 18, 2023 pm 01:39 PM

Solution to the problem that the php session disappears after refreshing: 1. Open the session through "session_start();"; 2. Write all public configurations in a php file; 3. The variable name cannot be the same as the array subscript; 4. In Just check the storage path of the session data in phpinfo and check whether the sessio in the file directory is saved successfully.

How to solve session failure How to solve session failure Oct 18, 2023 pm 05:19 PM

Session failure is usually caused by the session lifetime expiration or server shutdown. The solutions: 1. Extend the lifetime of the session; 2. Use persistent storage; 3. Use cookies; 4. Update the session asynchronously; 5. Use session management middleware.

What is the default expiration time of session php? What is the default expiration time of session php? Nov 01, 2022 am 09:14 AM

The default expiration time of session PHP is 1440 seconds, which is 24 minutes, which means that if the client does not refresh for more than 24 minutes, the current session will expire; if the user closes the browser, the session will end and the Session will no longer exist.

Solution to PHP Session cross-domain problem Solution to PHP Session cross-domain problem Oct 12, 2023 pm 03:00 PM

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains

How to solve the problem that the Springboot2 session timeout setting is invalid How to solve the problem that the Springboot2 session timeout setting is invalid May 22, 2023 pm 01:49 PM

Problem: Today, we encountered a setting timeout problem in our project, and changes to SpringBoot2’s application.properties never took effect. Solution: The server.* properties are used to control the embedded container used by SpringBoot. SpringBoot will create an instance of the servlet container using one of the ServletWebServerFactory instances. These classes use server.* properties to configure the controlled servlet container (tomcat, jetty, etc.). When the application is deployed as a war file to a Tomcat instance, the server.* properties do not apply. They do not apply,

How to implement SMS login in Redis shared session application How to implement SMS login in Redis shared session application Jun 03, 2023 pm 03:11 PM

1. Implementing SMS login based on session 1.1 SMS login flow chart 1.2 Implementing sending SMS verification code Front-end request description: Description of request method POST request path /user/code request parameter phone (phone number) return value No back-end interface implementation: @Slf4j@ ServicepublicclassUserServiceImplextendsServiceImplimplementsIUserService{@OverridepublicResultsendCode(Stringphone,HttpSessionsession){//1. Verify mobile phone number if

What are the differences between JavaScript and PHP cookies? What are the differences between JavaScript and PHP cookies? Sep 02, 2023 pm 12:29 PM

JavaScriptCookies Using JavaScript cookies is the most effective way to remember and track preferences, purchases, commissions and other information. Information needed for a better visitor experience or website statistics. PHPCookieCookies are text files that are stored on client computers and retained for tracking purposes. PHP transparently supports HTTP cookies. How do JavaScript cookies work? Your server sends some data to your visitor's browser in the form of a cookie. Browsers can accept cookies. If present, it will be stored on the visitor's hard drive as a plain text record. Now, when a visitor reaches another page on the site

See all articles