How to use the session function in ThinkPHP
这篇文章主要为大家详细介绍了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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

When passing a map to a function in Go, a copy will be created by default, and modifications to the copy will not affect the original map. If you need to modify the original map, you can pass it through a pointer. Empty maps need to be handled with care, because they are technically nil pointers, and passing an empty map to a function that expects a non-empty map will cause an error.
