Last active
June 4, 2018 18:05
-
-
Save arsisakarn/1450450 to your computer and use it in GitHub Desktop.
Symfony 2 set and read cookie
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
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;
}
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
nice, easy example