目录

CodeIgniter - Cookie管理( Cookie Management)

Cookie是从Web服务器发送到客户端计算机上的一小段数据。 CodeIgniter有一个名为“Cookie Helper”的帮助程序用于cookie管理。

Syntax

set_cookie( $name [, $value = '' [, $expire = '' [, $domain = '' [, $path = '/' [, $prefix = '' [, $secure = FALSE[, $httponly = FALSE ]]]]]]]])

Parameters

  • $namemixed ) - 此函数可用的所有参数的Cookie名称或关联数组

  • $valuestring ) - Cookie值

  • $expireint ) - 到期前的秒数

  • $domainstring ) - Cookie域名(通常为:.yourdomain.com)

  • $pathstring ) - Cookie路径

  • $prefixstring ) - Cookie名称前缀

  • $securebool ) - 是否只通过HTTPS发送cookie

  • $httponlybool ) - 是否从JavaScript隐藏cookie

Return Type

void

set_cookie()函数中,我们可以使用两种方式传递所有值。 在第一种方式中,只能传递数组,在第二种方式中,也可以传递单个参数。

Syntax

get_cookie( $index [, $xss_clean = NULL ]])

Parameters

  • $indexstring ) - Cookie名称

  • $xss_cleanbool ) - 是否对返回的值应用XSS过滤

Return

cookie值,如果未找到则为NULL

Return Type

mixed

get_cookie()函数用于获取使用set_cookie()函数设置的cookie。

Syntax

delete_cookie( $name [, $domain = '' [, $path = '/' [, $prefix = '' ]]]])

Parameters

  • $namestring ) - Cookie名称

  • $domainstring ) - Cookie域名(通常为:.yourdomain.com)

  • $pathstring ) - Cookie路径

  • $prefixstring ) - Cookie名称前缀

Return Type

void

delete_cookie()函数用于删除cookie()。

例子 (Example)

创建一个名为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中的routes.php文件,为上述控制器添加路由,并在文件末尾添加以下行。

$route['cookie'] = "Cookie_controller"; 
$route['cookie/display'] = "Cookie_controller/display_cookie"; 
$route['cookie/delete'] = "Cookie_controller/deletecookie";

之后,您可以在浏览器中执行以下URL来执行该示例。

http://yoursite.com/index.php/cookie

它将产生一个输出,如下面的屏幕截图所示。

cookie_management
↑回到顶部↑
WIKI教程 @2018