2 Methods to Set Cookie To Response Headers in Symfony 7

2 Methods to Set Cookie To Response Headers in Symfony 7

Symfony framework provides methods for manipulating cookies which will be sent along with the rest of the HTTP response headers.

This tutorial provides 2 methods to set cookie to the response headers in Symfony 7 application.

Method 1 - 'setCookie' method

The Response object stores headers in the public headers property. It is an instance of ResponseHeaderBag. The setCookie method can be used to add Cookie object to the response headers.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController
{
    #[Route('/')]
    public function index(): Response
    {
        $response = new Response();
        $response->headers->setCookie(new Cookie('name', 'John'));

        return $response;
    }
}

Method 2 - 'set' method

The ResponseHeaderBag class provides the set method that allows to set a header by name. We can use the set method to add the Set-Cookie HTTP response header and cookie as a string.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController
{
    #[Route('/')]
    public function index(): Response
    {
        $response = new Response();
        $response->headers->set('Set-Cookie', 'name=John');

        return $response;
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.