Skip to content

Instantly share code, notes, and snippets.

@yashuarc
Last active October 28, 2024 19:32
Show Gist options
  • Save yashuarc/10080747 to your computer and use it in GitHub Desktop.
Save yashuarc/10080747 to your computer and use it in GitHub Desktop.
Enabling CORS on CakePHP
public function beforeFilter() {
parent::beforeFilter();
$this->response->header('Access-Control-Allow-Origin','*');
$this->response->header('Access-Control-Allow-Methods','*');
$this->response->header('Access-Control-Allow-Headers','X-Requested-With');
$this->response->header('Access-Control-Allow-Headers','Content-Type, x-xsrf-token');
$this->response->header('Access-Control-Max-Age','172800');
}
@VIBHAY-KUMAR-PATEL
Copy link

Just in case: Inside bootstrap.php:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: *');
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

Thank you, I was struggling for a week to figure it out.

@elonmess
Copy link

Just in case: Inside bootstrap.php:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: *');
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

Thank you so much. This works perfectly for my case

@John-Henrique
Copy link

From CakePHP docs https://book.cakephp.org/4/en/controllers/request-response.html#setting-cross-origin-request-headers-cors

$this->response = $this->response->cors($this->request)
    ->allowOrigin(['*.cakephp.org'])
    ->allowMethods(['GET', 'POST'])
    ->allowHeaders(['X-CSRF-Token'])
    ->allowCredentials()
    ->exposeHeaders(['Link'])
    ->maxAge(300)
    ->build();

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