Home » Php » php – Symfony2 – how can I set custom CORS Headers?

php – Symfony2 – how can I set custom CORS Headers?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I want to set following Headers for TWIG Template from within my DefaultController:

header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Origin: http://www.mywebsite.com');
header('Access-Control-Allow-Headers: Content-Type, *');

Any suggestions how to do that?

How to&Answers:

from this article:

CorsListener.php

<?php
namespace MyCorp\MyBundle\Listener;

use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class CorsListener
{
    public function onKernelResponse(FilterResponseEvent $event)
    {   
        $responseHeaders = $event->getResponse()->headers;

        $responseHeaders->set('Access-Control-Allow-Headers', 'origin, content-type, accept');
        $responseHeaders->set('Access-Control-Allow-Origin', '*');
        $responseHeaders->set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, PATCH, OPTIONS');
    }   
}

services.yml

app.cors_listener:
    class:      MyCorp\MyBundle\Listener\CorsListener
    tags:
       - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }

Answer:

Using the response class:

use Symfony\Component\HttpFoundation\Response;
$response = new Response();
$response->headers->set('Content-Type', 'text/html');
$response->send();

Source/Documentation

Answer:

If its inside controller then use this:

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    public function indexAction()
    {
        ...    
        $response = new Response($xmlContent);
        $response->headers->set('Content-Type', 'xml');
        $response->headers->set('Another-Header', 'header-value');
        return $response;
    }
}

Just replace Content-Type with your header key and xml with value … etc

Answer:

If you are using the render() method of the controller, then you can add the necessary headers like below because render() method returns a Response object:

$response = $this->render('AppBundle:Post:index.html.twig', array('someArgs' => $someArgs));
$response->headers->set('Content-Type', 'text/html');
return $response;