Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 - how can I set custom CORS Headers?

Tags:

php

cors

symfony

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?

like image 631
Edge Avatar asked Dec 12 '11 09:12

Edge


4 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 }
like image 189
pleerock Avatar answered Nov 07 '22 04:11

pleerock


Using the response class:

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

Source/Documentation

like image 30
Steven Avatar answered Nov 07 '22 06:11

Steven


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

like image 3
TroodoN-Mike Avatar answered Nov 07 '22 04:11

TroodoN-Mike


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;
like image 2
egeogretmen Avatar answered Nov 07 '22 06:11

egeogretmen