lmribeiro
10/2/2018 - 10:28 AM

Cross Origin Resource Sharing with PHP & YII

Cross Origin Resource Sharing with PHP & YII

// 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'),
// 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");
// 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);
    }