FuelPHP - Cookie和会话管理

Cookie 提供客户端数据存储,它仅支持少量数据.通常,每个域2KB,这取决于浏览器. 会话提供服务器端数据存储,它支持大量数据.让我们来看看如何在FuelPHP Web应用程序中创建cookie和会话.

Cookies

FuelPHP提供 Cookie 类创建一个cookie项目. Cookie类用于创建,分配和删除cookie.

配置Cookie

可以通过主应用程序配置文件全局配置Cookie类,位于fuel/app/config/config.php.它定义如下.

'cookie' => array (  
   
   //Number of seconds before the cookie expires 
   'expiration'  => 0,  
   
   //Restrict the path that the cookie is available to 
   'path'        => '/',  
   
   //Restrict the domain that the cookie is available to 
   'domain'      => null,  
   
   // Only transmit cookies over secure connections 
   'secure'      => false,  
   
   // Only transmit cookies over HTTP, disabling Javascript access 
   'http_only'   => false, 
),

方法

Cookie类提供了创建,访问和方法的方法删除cookie项目.它们如下 :

set()

set方法用于创建Cookie变量.它包含以下参数,

  • $ name :  $ _COOKIE数组中的键.

  • $ value :  Cookie的价值.

  • $ expiration :  Cookie应该持续的秒数.

  • $ path : 服务器上可以使用cookie的路径.

  • $ domain :  Cookie可用的域.

  • $ secure : 如果您只想通过安全连接传输cookie,则设置为true.

  • $ httponly : 仅允许通过HTTP传输cookie,禁用JavaScript访问.

Cookie::set('theme', 'green');

get()

get方法用于读取Cookie变量.它包含以下参数,

  • $ name :  $ _COOKIE数组中的键.

  • $ value : 如果密钥不可用,则返回值$ _COOKIE数组.

Cookie::get('theme');

delete()

delete方法用于删除Cookie变量.它包含以下参数,

  • $ name :  $ _COOKIE数组中的键.

  • $ value :  Cookie的价值.

  • $ domain :  Cookie可用的域.

  • $ secure : 如果您只想通过安全连接传输cookie,则设置为true.

  • $ httponly : 仅允许通过HTTP传输cookie,禁用JavaScript访问.

 Cookie::delete('theme');

会话

FuelPHP提供类会话以维护应用程序的状态.

配置会话

可以通过特殊配置文件 fuel/core/config/session.php 配置会话类.一些重要的配置条目如下 :

  • auto_initialize : 自动初始化会话.

  • 驱动程序 : 会话驱动程序的名称.会话使用驱动程序实现,可能的选项包括cookie,db,memcached,redis和file.默认驱动程序是cookie.

  • match_ip : 检查客户端IP.

  • match_ua : 检查客户端用户代理.

  • expiration_time : 会话超时值以秒为单位.

  • rotation_time : 是时候更新会话了.

会话方法

会话类提供了操作会话的方法数据.它们如下所示,

instance()

实例方法返回默认或特定实例,按名称识别.

$session = Session::instance();            // default instance 
$session = Session::instance('myseesion'); // specific instance

set()

set 方法用于分配一个会话变量.

Session::set('userid', $userid);

get()

get 方法允许您从中检索存储的变量会话.

$userid = Session::get('userid');

delete()

删除方法允许您删除存储的会话变量.

Session::delete('userid');

create()

create 方法允许您创建新会话.如果会话已经存在,它将被销毁并创建一个新会话.

Session::create();

destroy()

destroy 方法用于销毁现有会话.

Session::destroy();

read()

读取方法允许您阅读会话.

Session::read();

write()

方法允许您编写会话.

Session::write();

key()

方法允许您检索会话密钥的元素.密钥的值是唯一的.

$session_id = Session::key('session_id');