如何在cakephp 2中阅读cookie

时间:2014-04-16 10:29:06

标签: php cakephp cookies cakephp-2.0

我想在用户登录时编写cookie,并希望下次当用户打开该页面时,它会在登录前读取cookie名称并显示。 foloowing是我使用的代码: -

var $components = array('Cookie');

function beforeFilter()
{
    $this->Cookie->name = 'LOGIN_COOKIE';
    $this->Cookie->time = time()+60*60*24*30;  //cookie expire after 30 days 
    $this->Cookie->path = '/';
    $this->Cookie->domain = 'example.com/';
    $this->Cookie->secure = false;
    $this->Cookie->key = '39lbkutg1i2l0kta6785d8qki5';
    $this->Cookie->httpOnly = true;
}

登录功能

$this->Cookie->write('COOKIE_USER', array(
                      'name' => $UserDetails['SystemUser']['Name'], 
                      'email' => $UserDetails['SystemUser']['email'],
                      'lastname' => $UserDetails['SystemUser']['LastName']
));

在我的视图中

$readCookie=$this->Cookie->read('COOKIE_USER');

但它给出了错误"缺少助手"

     Error: CookieHelper could not be found.
     Error: Create the class CookieHelper below in file: app/View/Helper/CookieHelper.php

请指导我。

3 个答案:

答案 0 :(得分:1)

控制器中的

执行此操作

//Write enter code here
$this->set('readCookie', $this->Cookie->write('COOKIE_USER'=> array(
                      'name' => $UserDetails['SystemUser']['Name'], 
                      'email' => $UserDetails['SystemUser']['email'],
                      'lastname' => $UserDetails['SystemUser']['LastName']
)));

//Read
$this->set('readCookie', $this->Cookie->read('COOKIE_USER'));


//write into a key
$this->Cookie->write('COOKIE_USER.name'=>'Piya');
//Read a key
$this->set('username', $this->Cookie->read('COOKIE_USER.name'));

然后在你看来

debug($readCookie);
echo $username;

如果您不需要,请评论这些

//function beforeFilter()
//{
//    $this->Cookie->name = 'LOGIN_COOKIE';
//    $this->Cookie->time = time()+60*60*24*30;  //cookie expire after 30 days 
//    $this->Cookie->path = '/';
//    $this->Cookie->domain = 'example.com/';
//    $this->Cookie->secure = false;
//    $this->Cookie->key = '39lbkutg1i2l0kta6785d8qki5';
//    $this->Cookie->httpOnly = true;
//}

look at this example

答案 1 :(得分:0)

在控制器中试用此代码

ThreadPoolExecutor

答案 2 :(得分:-1)

阅读控制器使用的cookie -

$this->Cookie->read()

要在View上阅读cookie -

CookieComponent::read();