Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

symfony - Read and Write Cookie in Symfony2

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...