Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save voronoy/5303c444fd525ce64417 to your computer and use it in GitHub Desktop.
Save voronoy/5303c444fd525ce64417 to your computer and use it in GitHub Desktop.
CakePHP 2 CORS
<?php
App::uses('DispatcherFilter', 'Routing');
/**
* Api Cors Dispatcher
*/
class ApiCorsDispatcher extends DispatcherFilter {
public $priority = 1;
public function beforeDispatch(CakeEvent $event) {
$request = $event->data['request'];
$response = $event->data['response'];
$origin = filter_has_var(INPUT_SERVER, 'HTTP_ORIGIN') ? filter_input(INPUT_SERVER, 'HTTP_ORIGIN') : '*';
$response->header('Access-Control-Allow-Origin', $origin);
$response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
if (filter_has_var(INPUT_SERVER, 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS')) {
$response->header('Access-Control-Allow-Headers', filter_input(INPUT_SERVER, 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS'));
}
if ($request->is('OPTIONS')) {
$event->stopPropagation();
return $response;
}
}
}
@voronoy
Copy link
Author

voronoy commented Jul 31, 2014

bootstrap.php:

Configure::write('Dispatcher.filters', array(
'ApiCorsDispatcher',
));

@RT-TL
Copy link

RT-TL commented Jan 24, 2017

@voronY: The whole topic might be a bit out of date but I am struggling with CORS request in my CakePHP 2.8 installation. I find the cookbook not very helpful in this matter. Can you help my understanding how I need to use the dispatcher if I want to make a controller action able of accepting CORS requests?

@jowusu837
Copy link

Good job @voronoy

@gildonei
Copy link

Great work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment