4

As the title suggests,

Here's the code...

public function index(Request $request, Application $app)
{
    $cookies = $request->cookies;
    print_r($request->cookies);
    if(!$cookies->has("recordsPerPage"))
    {
        $response = new Response();
        $cookie = new Cookie("recordsPerPage", $app['defaultRecordsPerPage']);
        $response->headers->setCookie($cookie); 
    }
    print_r($request->cookies);exit; //prints nothing here !!
}

I also tried to set it in a $app->after() but failed. do you have any other ways to set cookies other than in controller.

Thank you.

Leigh
  • 12,859
  • 3
  • 39
  • 60
hardik
  • 9,141
  • 7
  • 32
  • 48
  • I dont know why it is down voted !!! i tried [this](http://stackoverflow.com/questions/13021440/silex-set-cookie), [this](http://stackoverflow.com/questions/8432281/symfony2-read-cookie), and [this](http://stackoverflow.com/questions/7727442/read-and-write-cookie-in-symfony2). somebody says you need to get it `$response->headers->getCookies()` some says you need to get it from `$request->cookies`. i tried both. – hardik Jan 27 '13 at 14:18

1 Answers1

7

Cookies are set with response and available on next request. So you have to return the response with this cookie, and if you want it to be available on the request, make it a redirect response so the browser will set cookie and issue next request with this newly created cookie:

$cookies = $request->cookies;
if(!$cookies->has("recordsPerPage"))
{
    $cookie = new Cookie("recordsPerPage", $app['defaultRecordsPerPage']);
    $response = Response::create('', 302, array("Location" => "http://127.0.0.1/whatever/"));
    $response->headers->setCookie($cookie);
    return $response;
}else{
    return print_r($cookies, 1);
}

Other possibility is to set this cookie directly in the request ($request->cookies->set('recordsPerPage', $app['defaultRecordsPerPage']);) but you still have to return response with this cookie to set it in the browser.

dev-null-dweller
  • 29,274
  • 3
  • 65
  • 85