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

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

问题描述

我想在本地浏览器 cookie 中存储一些信息.经过几个小时寻找一个不错的教程,我设法在非会话 cookie 中存储了一些数据:

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:

控制器 - 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();

我想知道这是否是正确的方法.此外,我尝试了几种使用 HttpFoundation 组件读取 cookie 的方法,但没有成功.除了通过 $_COOKIE['mycookie'] 访问 cookie 之外,还有其他方法吗?

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'] ?

这是我尝试读取 cookie 的地方

Here is where I try to read the cookie

控制器 - 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();

应该返回 ResponseHeaderBag 类中的 cookie 数组以获取有关该函数的更多信息

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

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

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