CodeIgniter教程:Cookie管理
Cookie是从网络服务器发送的小块数据,存储在客户的计算机上。CodeIgniter内置一个名为“Cookie Helper”的类用于Cookie管理。
语法
set_cookie($name[, $value = ''[, $expire = ''[, $domain = ''[, $path = '/'[, $prefix = ''[, $secure = FALSE[, $httponly = FALSE]]]]]]]])
参数
$name (mixed) − 此函数可用的所有参数的Cookie名称或关联数组
$value (string) − Cookie值
$expire (int) − 过期时间,单位秒
$domain (string) − Cookie 域名
$path (string) − Cookie路径
$prefix (string) − Cookie名称的前缀
$secure (bool) −是否只通过HTTPS发送Cookie
$httponly (bool) − 是否对JavaScript隐藏cookie
返回类型
void
在set_cookie()函数中,我们可以用两种方法传递值。在第一种方式中,只传递数组,在第二种方式中,也可以传递单个参数。
语法
get_cookie($index[, $xss_clean = NULL]])
参数
$index (string) − Cookie名字
$xss_clean (bool) − 是否对返回值过滤XSS
返回值
cookie值,如果找不到,则为空
返回类型
mixed
get_cookie()函数用于获取使用set_cookie()函数设置的cookie。
语法
delete_cookie($name[, $domain = ''[, $path = '/'[, $prefix = '']]]])
参数
$name (string) − Cookie名
$domain (string) − Cookie域
$path (string) − Cookie路径
$prefix (string) − Cookie名前缀
返回类型
void
delete_cookie()函数用于删除cookie。
例子
创建一个名为Cookie_controller.php的控制器,并将其保存在application/controller/Cookie_controller.php。
<?php class Cookie_controller extends CI_Controller { function __construct() { parent::__construct(); $this->load->helper(array('cookie', 'url')); } public function index() { set_cookie('cookie_name','cookie_value','3600'); $this->load->view('Cookie_view'); } public function display_cookie() { echo get_cookie('cookie_name'); $this->load->view('Cookie_view'); } public function deletecookie() { delete_cookie('cookie_name'); redirect('cookie/display'); } } ?>
创建一个名为Cookie_view.php的视图文件,并将其保存在application/views/Cookie_view.php中。
<!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>CodeIgniter View Example</title> </head> <body> <a href = 'display'>Click Here</a> to view the cookie.<br> <a href = 'delete'>Click Here</a> to delete the cookie. </body> </html>
修改application/config/routes.php文件,为上述控制器添加路由,并在文件末尾添加以下行。
$route['cookie'] = "Cookie_controller"; $route['cookie/display'] = "Cookie_controller/display_cookie"; $route['cookie/delete'] = "Cookie_controller/deletecookie";
之后,您可以在浏览器中执行以下网址来执行该示例。
http://yoursite.com/index.php/cookie
它将产生一个输出,如下图所示。