在 Symfony2 中读写 Cookie

发布于 2024-12-09 12:33:02 字数 1069 浏览 1 评论 0原文

我想在本地浏览器cookie中存储一些信息。经过几个小时寻找一个不错的教程后,我设法将一些数据存储在非会话 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();

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

这是我尝试读取 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);
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

还不是爱你 2024-12-16 12:33:03
$response->headers->getCookies();

应该返回一个 cookies 数组,查看 ResponseHeaderBag 类以获取有关该函数的更多信息

$response->headers->getCookies();

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

柳若烟 2024-12-16 12:33:03

这对于尝试在 symfony2 中制作 cookie 的人很有用:

use Symfony\Component\HttpFoundation\Cookie;

this can be useful for someone trying to make cookies in symfony2 :

use Symfony\Component\HttpFoundation\Cookie;
从此见与不见 2024-12-16 12:33:03

如何使用 Cookie 和 Session 的示例:

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    public function indexAction()
    {
        // Set session value
        $session = $this->getRequest()->getSession();
        $session->set('test', 1);

        // Get session value
        $value = $session->get('test');

        // Set cookie value
        $response = new Response();
        $cookie = new Cookie('test', 1, time()+3600);
        $response->headers->setCookie($cookie);

        // Get cookie value
        $this->getRequest()->cookies->get('test');
    }
}

Example how to use Cookies and Session:

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    public function indexAction()
    {
        // Set session value
        $session = $this->getRequest()->getSession();
        $session->set('test', 1);

        // Get session value
        $value = $session->get('test');

        // Set cookie value
        $response = new Response();
        $cookie = new Cookie('test', 1, time()+3600);
        $response->headers->setCookie($cookie);

        // Get cookie value
        $this->getRequest()->cookies->get('test');
    }
}
不必你懂 2024-12-16 12:33:03
            use Symfony\Component\HttpFoundation\Cookie;
            use Symfony\Component\HttpFoundation\Response;

            // set current active tab in cookie 
            $cookie = new Cookie('myProfileActiveTab', 'myaddress', strtotime('now + 60 minutes'));
            $response = new Response();
            $response->headers->setCookie($cookie);
            $response->send();


           // get current active tab from cookies
           $cookies = $request->cookies;
           if ($cookies->has('myProfileActiveTab')) {
               $activetab = $cookies->get('myProfileActiveTab');
           } 
            use Symfony\Component\HttpFoundation\Cookie;
            use Symfony\Component\HttpFoundation\Response;

            // set current active tab in cookie 
            $cookie = new Cookie('myProfileActiveTab', 'myaddress', strtotime('now + 60 minutes'));
            $response = new Response();
            $response->headers->setCookie($cookie);
            $response->send();


           // get current active tab from cookies
           $cookies = $request->cookies;
           if ($cookies->has('myProfileActiveTab')) {
               $activetab = $cookies->get('myProfileActiveTab');
           } 
无语# 2024-12-16 12:33:03

更多有趣的 cookies 信息链接(symfony2 的 http_fundation 组件):

Symfony2 http_fundation 组件

Symfony2 http_fundation api

Symfony2 http_fundation 组件 (西班牙语)

More interesting cookies information links (http_fundation component for symfony2):

Symfony2 http_fundation component

Symfony2 http_fundation api

Symfony2 http_fundation component (spanish)

手心的温暖 2024-12-16 12:33:02

这才是设置cookie的正确方法。
要读取已在浏览器中写入的 cookie,请执行以下操作:

$request->cookies->get('myCookie');

但是在我在 $response 对象中创建 cookie 之后:

$cookie = new Cookie('myCookie', 'contentOfMyCookie');
$response = new Response();
$response->headers->setCookie($cookie);

我调用此方法:

$response->headers->getCookies();

我得到一个 cookie 数组,这些 cookie 将被写入浏览器中 - 而不是那些已经存在于浏览器中的 cookie。

形象地说,在 $request 和 $response 之间有一个执行控制器代码的时间。

此外,在 twig 模板中,您可以使用

{{ app.request.cookies.get('myCookie') }}

这样的方式获取已在浏览器中写入的 cookie 的值,而不是从 $response 对象中获取的值!从浏览器新创建的 cookie,您只能在重新加载页面后才能读取(ajax 不需要重新加载整个页面)。

总而言之,您可以使用$request对象读取cookie,并使用$response对象创建它们。 (显然,由于某些原因,您也可以读取 $response 对象 cookie - 但这些情况相当罕见)。

This is the correct way of setting cookie.
To read cookie already written in the browser do:

$request->cookies->get('myCookie');

But after I created cookie in the $response object:

$cookie = new Cookie('myCookie', 'contentOfMyCookie');
$response = new Response();
$response->headers->setCookie($cookie);

I call this method:

$response->headers->getCookies();

I get an array of cookies, which are to be written in the browser - not those already existing there.

Figuratively, between $request and $response there is a time of executing controller's code.

Besides, in a twig template you can use

{{ app.request.cookies.get('myCookie') }}

you thus get value of the cookie already written in the browser, not that from the $response object! Newly created cookie from the browser you can read only after having reloaded page (ajax doesn't need to reload whole page).

To sum it up, you can read cookies using $request object, and create them with $response object. (Obviously, for some reasons, you can also read $response object cookies - but these are rather rare situations).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文