Created
July 31, 2014 10:25
-
-
Save voronoy/5303c444fd525ce64417 to your computer and use it in GitHub Desktop.
CakePHP 2 CORS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} | |
} |
@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?
Good job @voronoy
Great work!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
bootstrap.php:
Configure::write('Dispatcher.filters', array(
'ApiCorsDispatcher',
));