Reputation: 43
I have a cookie setup code.
public function checkInviter(int $inviter)
{
$response = new RedirectResponse($this->generateUrl('app_homepage'));
if ($inviter > 0) {
$response->headers->setCookie(Cookie::create('_inviter_id', $inviter, new \DateTime("+ 30 days")));
$response->sendHeaders();
}
return $response;
}
Further in the registration I want to delete / clear it. If I create a new response, then he does not know about the cookies set. How to work with cookies?
public function register() {
$response = new Response();
dump($response); // cleared Response
$response->headers->removeCookie('_inviter_id', '/', null);
$response->send();
return $this->render('security/register.html.twig');
}
I found some answer, but it is not entirely accurate.
Upvotes: 2
Views: 10530
Reputation: 12105
You are duplicating the generation of responses: there are technically two different responses sent out, as you generate one in your controller and Symfony creates a second one during $this->render
.
You should reuse your own Response object by setting it as the third parameter of render
to avoid problems. The full code might look as following (reusing the method clearCookie
which you've already found):
public function register() {
$response = new Response();
$response->headers->clearCookie('_inviter_id', '/', null);
return $this->render('security/register.html.twig', [], $response);
}
Upvotes: 7
Reputation: 43
Testing the code, I found a solution. Use
$response->headers->clearCookie('_inviter_id');
This clears the value and sets a new expiration date.
Upvotes: 0