FuelPHP Cookie
Cookie 提供客户端数据存储,仅支持少量数据。通常,每个域为 2KB,这取决于浏览器。
Session 提供服务器端数据存储,支持海量数据。让我们来看看如何在 FuelPHP Web 应用程序中创建 cookie 和会话。
Cookie
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 数组中不可用时返回的值。
delete()
delete 方法用于删除一个 Cookie 变量。它包含以下参数,
$name-$_COOKIE 数组中的键。
$value-cookie 的值。
$domain-cookie 可用的域。
$secure-如果您只想通过安全连接传输 cookie,请设置为 true。
$httponly-仅允许通过 HTTP 传输 cookie,禁用 JavaScript 访问。
会话
FuelPHP 提供类,
Session 来维护应用程序的状态。
配置会话
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 方法返回默认或特定实例,由名称标识。
$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 方法允许您创建一个新会话。如果会话已经存在,它将被销毁并创建一个新会话。
destroy()
destroy 方法用于销毁现有会话。
read()
read 方法允许您读取会话。
write()
write 方法允许您编写会话。
key()
key 方法允许您检索会话密钥的元素。键的值是唯一的。
$session_id = Session::key('session_id');