目录

Cookie和会话管理(Cookie & Session Management)

Cookie提供客户端数据存储,仅支持少量数据。 通常,每个域2KB,这取决于浏览器。 Session提供服务器端数据存储,它支持大量数据。 让我们来看看如何在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, 
), 

方法 (Methods)

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');

Session

FuelPHP提供类, Session来维护应用程序的状态。

配置会话

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

  • auto_initialize - 自动初始化会话。

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

  • match_ip - 检查客户端IP。

  • match_ua - 检查客户端用户代理。

  • expiration_time - 会话超时值,以秒为单位。

  • rotation_time - 续订会话的时间。

会话方法

Session类提供了操作会话数据的方法。 它们如下,

instance()

instance方法返回默认或特定实例,该实例由n​​ame标识。

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

set()

set方法用于分配Session变量。

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

get()

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

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

delete()

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

Session::delete('userid');

create()

create方法允许您创建新会话。 如果会话已存在,则会销毁该会话并创建新会话。

Session::create(); 

destroy()

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

Session::destroy();

read()

read方法允许您读取会话。

Session::read(); 

write()

write方法允许您编写会话。

Session::write();

key()

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

$session_id = Session::key('session_id'); 
↑回到顶部↑
WIKI教程 @2018