php Symfony2:读取 Cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8432281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:41:36  来源:igfitidea点击:

Symfony2 : Read Cookie

phpsymfonycookies

提问by Matt

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:

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

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) { } 
}

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

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

Thanks in advance

提前致谢

回答by AlterPHP

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

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

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

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