Symfony2:读取Cookie [英] Symfony2 : Read Cookie

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

问题描述

我在Controller操作中设置了几个Cookie,然后在另一个操作中,我想读取cookie集合并使用值进行操作。但是,当尝试读取cookie时,我看到的是一个空数组,我的代码如下:

I've set a few cookies in a Controller action and then in another action I want to read the cookie set and do something with the value. However, when trying to read the cookies, all i see is an empty array, my code is as follows:

public function testSetCookieAction()
{
    $value = 'ABCDEFGHI'

    $cookie = new Cookie('SYMFONY2_TEST', $value, (time() + 3600 * 24 * 7), '/');
    $response = new Response();
    $response->headers->setCookie($cookie);
    $response->send();  
.
.
.
}

public function testReadCookieAction()
{
    $response = new Response();
$cookies = $response->headers->getCookies();

// $cookies = array(0) { } 
}

当我 var_dump($ _ COOKIE); ,我看到 array(1){[SYMFONY2_TEST] => string(9)ABCDEFGHI} 有人知道我做错了什么吗?

When i var_dump($_COOKIE);, I see array(1) { ["SYMFONY2_TEST"]=> string(9) "ABCDEFGHI" } Does anybody know what I am doing wrong?

提前感谢

推荐答案

您必须在Request对象上读取Cookie,而不是在您刚刚创建的void Response对象上);

You must read cookies on the Request object, not on the void Response object you just created ;)

public function testReadCookieAction(Request $request)
{
    $cookies = $request->cookies;

    if ($cookies->has('SYMFONY2_TEST'))
    {
        var_dump($cookies->get('SYMFONY2_TEST'));
    }
}

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

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