Skip to content

Instantly share code, notes, and snippets.

@goliatone
Forked from sourcec0de/ApiController.php
Last active December 27, 2015 12:49
Show Gist options
  • Save goliatone/7329068 to your computer and use it in GitHub Desktop.
Save goliatone/7329068 to your computer and use it in GitHub Desktop.
# WE CAN ALSO ENABLE CORS IN htaccess
# with AJAX withCredentials=false (cookies NOT sent)
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, PATCH, DELETE"
Header always set Access-Control-Allow-Headers "X-Accept-Charset,X-Accept,Content-Type"
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L,E=HTTP_ORIGIN:%{HTTP:ORIGIN}]]
// add this to your API controller in Yii
public function actionPreflight() {
$content_type = 'application/json';
$status = 200;
// set the status
$status_header = 'HTTP/1.1 ' . $status . ' ' . $this->_getStatusCodeMessage($status);
header($status_header);
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Authorization");
header('Content-type: ' . $content_type);
}
// Where ever the function "_sendResponse" is located
// add these lines, this will allow CORS
// Allows from any origin
// Allows a header called Authorization
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Authorization");
// REST CORS pattern
// A preflight request is basically an OPTIONS request to ask for permission to use cross-domain features.
// So we have add the proper verb in the url manager rules (config/main.php):
array('api/preflight', 'pattern'=>'api/*', 'verb'=>'OPTIONS'),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment