Skip to content

Instantly share code, notes, and snippets.

@arsisakarn
Last active June 4, 2018 18:05
Show Gist options
  • Save arsisakarn/1450450 to your computer and use it in GitHub Desktop.
Save arsisakarn/1450450 to your computer and use it in GitHub Desktop.
Symfony 2 set and read cookie
<?php
public function testSetCookieAction()
{
$value = '12345';
$html = '<html><body>test set cookie varName =' . $value . '</body></html>';
$response = new Response($html);
$response->headers->setCookie(new Cookie('varName', $value, time() + (3600 * 48)));
return $response;
}
public function testReadCookieAction()
{
$request = $this->getRequest();
$cookies = $request->cookies->all();
$html = '<html><body>test read cookie varName =' . $cookies["varName"] . '</body></html>';
$response = new Response($html);
return $response;
}
@merdocif
Copy link

merdocif commented Nov 7, 2014

Your code is simple and intuitive but you omitted one detail.
Your code:

public function testSetCookieAction()
    {
        $value = '12345';
        $html = '<html><body>test set cookie varName =' . $value . '</body></html>';
        $response = new Response($html);          
        $response->headers->setCookie(new Cookie('varName', $value, time() + (3600 * 48))); 
        return $response; 
    }

My modification of your code:

public function testSetCookieAction()
    {
        $value = '12345';
        $html = '<html><body>test set cookie varName =' . $value . '</body></html>';
        $response = new Response($html);          
        $response->headers->setCookie(new Cookie('varName', $value, time() + (3600 * 48))); 
        $response->send();
        return $response; 
    }

@saranraj
Copy link

saranraj commented Jul 26, 2016

To clear the cookie variable

$response = new Response(); $response->headers->clearCookie('varName'); $response->send();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment