zl程序教程

您现在的位置是:首页 >  其它

当前栏目

pahlcon:cookies设置

设置 cookies
2023-09-14 08:57:52 时间

非加密方式(简单,但不推荐)

步骤 1

在全局容器中加入Cookie:

 $di->set('cookies', function () {
        $cookies = new \Phalcon\Http\Response\Cookies();
        $cookies->useEncryption(false); //默认使用加密方式,但这里我们刚开始使用非加密方式
        return $cookies;
    });

  

 

步骤 2

首先,需要在用户登陆时根据用户的输入信息生成cookies,然后存储在cookies中,并设置好失效的时间。 
如下所示:

//设备变量name=xxx,有效时间为未来一周
$this->cookies->set('name', 'xxx', time() + 7 * 86400);
$this->cookies->set('passwd', 'xxx', time() + 7 * 86400);

  

 

步骤 3

通常Phalcon的项目中会使用ACL进行用户的访问控制,而要实现用户在任何时间打开浏览器直接访问,就需要在ACL控制逻辑中获取Cookie中的值进行判断。

//获得name
$this->cookies->get('name')->getValue();
$this->cookies->get('passwd')->getValue();

  



加密方式(推荐)

加密方式是默认的Cookie方式,但在使用前必须满足以下条件:

1. 在全局容器中加入crypt并定义key,即:

  $di->set('cookies', function () {
        $cookies = new \Phalcon\Http\Response\Cookies();
//        $cookies->useEncryption(false);
        return $cookies;
    });

    $di->set('crypt', function (){
        $crypt = new Phalcon\Crypt();
        $crypt->setKey('xxxxxx'); //salt
        return $crypt;
    });

  

2. 由于crypt依赖于php中的mcrypt扩展,所以必须安装

3. 使用加密方式后,Phalcon中有一个bug存在,即在以下代码中获取数据时会有空白字符:

//获得name
$this->cookies->get('name')->getValue();
$this->cookies->get('passwd')->getValue();

  

 

必须改成:

trim($this->cookies->get('name')->getValue());
trim($this->cookies->get('passwd')->getValue());