Skip to content
PHP Ecosystem
Explore

Cors

API reference › yii › filters › Cors

Cors filter implements Cross Origin Resource Sharing.

Make sure to read carefully what CORS does and does not. CORS do not secure your API, but allow the developer to grant access to third party code (ajax calls from external domain).

You may use CORS filter by attaching it as a behavior to a controller or module, like the following,

public function behaviors()
{
return [
'corsFilter' => [
'class' => \yii\filters\Cors::class,
],
];
}

The CORS filter can be specialized to restrict parameters, like this, MDN CORS Information

public function behaviors()
{
return [
'corsFilter' => [
'class' => \yii\filters\Cors::class,
'cors' => [
// restrict access to
'Origin' => ['http://www.myserver.com', 'https://www.myserver.com'],
// Allow only POST and PUT methods
'Access-Control-Request-Method' => ['POST', 'PUT'],
// Allow only headers 'X-Wsse'
'Access-Control-Request-Headers' => ['X-Wsse'],
// Allow credentials (cookies, authorization headers, etc.) to be exposed to the browser
'Access-Control-Allow-Credentials' => true,
// Allow OPTIONS caching
'Access-Control-Max-Age' => 3600,
// Allow the X-Pagination-Current-Page header to be exposed to the browser.
'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
],
],
];
}

For more information on how to add the CORS filter to a controller, see the Guide on REST controllers.

PropertyTypeDescriptionDefined by
$actionsarrayDefine specific CORS rules for specific actions Default: [].Cors
$corsarrayBasic headers handled for the CORS requests. Default: ['Origin' => ['*'], 'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'], 'Access-Control-Request-Headers' => ['*'], 'Access-Control-Allow-Credentials' => null, 'Access-Control-Max-Age' => 86400, 'Access-Control-Expose-Headers' => []].Cors
$exceptarrayList of action IDs that this filter should not apply to. Default: [].yii\base\ActionFilter
$onlyarrayList of action IDs that this filter should apply to. Default: [].yii\base\ActionFilter
$owneryii\base\T|nullThe owner of this behavior Default: null.yii\base\Behavior
$requestyii\web\Request|nullThe current request. Default: null.Cors
$responseyii\web\Response|nullThe response to be sent. Default: null.Cors
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\BaseObject
__get()Returns the value of an object property.yii\base\BaseObject
__isset()Checks if a property is set, i.e. defined and not null.yii\base\BaseObject
__set()Sets value of an object property.yii\base\BaseObject
__unset()Sets an object property to null.yii\base\BaseObject
addCorsHeaders()Adds the CORS headers to the response.Cors
afterAction()This method is invoked right after an action is executed.yii\base\ActionFilter
afterFilter()yii\base\ActionFilter
attach()Attaches the behavior object to the component.yii\base\ActionFilter
beforeAction()This method is invoked right before an action is to be executed (after all possible filters.) You may override this method to do last-minute preparation for the action.Cors
beforeFilter()yii\base\ActionFilter
canGetProperty()Returns a value indicating whether a property can be read.yii\base\BaseObject
canSetProperty()Returns a value indicating whether a property can be set.yii\base\BaseObject
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
detach()Detaches the behavior object from the component.yii\base\ActionFilter
events()Declares event handlers for the $owner’s events.yii\base\Behavior
extractHeaders()Extract CORS headers from the request.Cors
hasMethod()Returns a value indicating whether a method is defined.yii\base\BaseObject
hasProperty()Returns a value indicating whether a property is defined.yii\base\BaseObject
init()Initializes the object.yii\base\BaseObject
overrideDefaultSettings()Override settings for specific action.Cors
prepareHeaders()For each CORS headers create the specific response.Cors
getActionId() protectedReturns an action ID by converting Action::$uniqueId into an ID relative to the module.yii\base\ActionFilter
headerize() protectedConvert any string (including php headers with HTTP prefix) to header format.Cors
headerizeToPhp() protectedConvert any string (including php headers with HTTP prefix) to header format.Cors
isActive() protectedReturns a value indicating whether the filter is active for the given action.yii\base\ActionFilter
prepareAllowHeaders() protectedHandle classic CORS request to avoid duplicate code.Cors
public yii\web\Request|null $request = null

The current request.

If not set, the request application component will be used.

public yii\web\Response|null $response = null

The response to be sent.

If not set, the response application component will be used.

public function addCorsHeaders(yii\web\Response $response, array $headers): mixed

Adds the CORS headers to the response.

Parameters

ParameterTypeDescription
$responseyii\web\Response
$headersarrayCORS headers which have been computed

Returns

mixed

public function beforeAction(mixed $action): bool

This method is invoked right before an action is to be executed (after all possible filters.) You may override this method to do last-minute preparation for the action.

Parameters

ParameterTypeDescription
$actionmixedThe action to be executed.

Returns

bool: Whether the action should continue to be executed.

public function extractHeaders(): array

Extract CORS headers from the request.

Returns

array: CORS headers to handle

public function overrideDefaultSettings(yii\base\Action $action): mixed

Override settings for specific action.

Parameters

ParameterTypeDescription
$actionyii\base\ActionThe action settings to override

Returns

mixed

public function prepareHeaders(array $requestHeaders): array

For each CORS headers create the specific response.

Parameters

ParameterTypeDescription
$requestHeadersarrayCORS headers we have detected

Returns

array: CORS headers ready to be sent

protected function headerize(string $string): string

Convert any string (including php headers with HTTP prefix) to header format.

Example:

  • X-PINGOTHER -> X-Pingother
  • X_PINGOTHER -> X-Pingother

Parameters

ParameterTypeDescription
$stringstringString to convert

Returns

string: The result in “header” format

protected function headerizeToPhp(string $string): string

Convert any string (including php headers with HTTP prefix) to header format.

Example:

  • X-Pingother -> HTTP_X_PINGOTHER
  • X PINGOTHER -> HTTP_X_PINGOTHER

Parameters

ParameterTypeDescription
$stringstringString to convert

Returns

string: The result in “php $_SERVER header” format

protected function prepareAllowHeaders(string $type, array $requestHeaders, array &$responseHeaders): mixed

Handle classic CORS request to avoid duplicate code.

Parameters

ParameterTypeDescription
$typestringThe kind of headers we would handle
$requestHeadersarrayCORS headers request by client
$responseHeadersarrayCORS response headers sent to the client

Returns

mixed