在Symfony2中读取和写入Cookie [英] Read and Write Cookie in Symfony2

查看:121
本文介绍了在Symfony2中读取和写入Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在本地浏览器Cookie中存储一些信息。过了几个小时后,我设法在非会话cookie中存储了一些数据:



controller - indexAction() p>

  $ cookieGuest = array(
'name'=>'mycookie',
'value'=> ;'testval',
'path'=> $ this-> generateUrl('my_route'),
'time'=> time()+ 3600 * 24 * 7
);

$ cookie = new Cookie($ cookieGuest ['name'],$ cookieGuest ['value'],$ cookieGuest ['time'],$ cookieGuest ['path']);

$ response = new Response();
$ response-> headers-> setCookie($ cookie);
$ response-> send();

我想知道这是否是正确的方法。此外,我尝试了几种方法来读取cookie与HttpFoundation组件,但没有成功。除了通过 $ _ COOKIE ['mycookie'] 访问Cookie的另一种方法吗?



这里是我尝试读取cookie

controller - cookieAction()

  function cookieAction($ _ locale,$ branch,$ page)
{
$ response = new Response();
$ cookies = $ response-> headers-> getCookies();

var_dump($ cookie);

// TODO:从cookie获取param(如果可用)

return $ this-> indexAction($ _ locale,$ branch,$ page);
}


解决方案

  $ response-> headers-> getCookies(); 

应该返回一个Cookie数组,在ResponseHeaderBag类中查看该函数的更多信息


I want to store some information in the local browser cookie. After hours looking for a nice tutorial, I managed to store some data in a non-session cookie:

controller - indexAction()

$cookieGuest = array(
    'name'  => 'mycookie',
    'value' => 'testval',
    'path'  => $this->generateUrl('my_route'),
    'time'  => time() + 3600 * 24 * 7
);

$cookie = new Cookie($cookieGuest['name'], $cookieGuest['value'], $cookieGuest['time'], $cookieGuest['path']);

$response = new Response();
$response->headers->setCookie($cookie);
$response->send();

I wonder if this is the correct way. Furthermore I tried several ways to read the cookie with the HttpFoundation Component, but without success. Is there another way than accessing the cookie via $_COOKIE['mycookie'] ?

Here is where I try to read the cookie

controller - cookieAction()

public function cookieAction($_locale, $branch, $page) 
{   
    $response = new Response();
    $cookies = $response->headers->getCookies();

    var_dump($cookies);

// TODO: Get params for indexAction from cookie if available

    return $this->indexAction($_locale, $branch, $page);
}

解决方案

$response->headers->getCookies();

should return an array of cookies look in ResponseHeaderBag class for more information about that function

这篇关于在Symfony2中读取和写入Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆