Skip to content

Instantly share code, notes, and snippets.

@swashata
Created August 13, 2021 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save swashata/00925ea541096cf2fee7de5d85b1e8d4 to your computer and use it in GitHub Desktop.
Save swashata/00925ea541096cf2fee7de5d85b1e8d4 to your computer and use it in GitHub Desktop.
CORS in WordPress Plugin
<?php
// CHECK BLOG POST HERE
// https://www.wpeform.io/blog/handle-cors-preflight-php-wordpress/
function acme_preflight_api() {
// preset option for allowed origins for our API server
$allowed_origins = [
'https://yoursite.com',
'https://preflight.yoursite.com',
'https://app.yoursite.com',
];
$request_origin = isset( $_SERVER['HTTP_ORIGIN'] )
? $_SERVER['HTTP_ORIGIN']
: null;
// if there is no HTTP_ORIGIN, then set current site URL
if ( ! $request_origin ) {
$request_origin = site_url( '' );
}
// a fallback value for allowed_origin we will send to the response header
$allowed_origin = 'https://yoursite.com';
// now determine if request is coming from allowed ones
if ( in_array( $request_origin, $allowed_origins ) ) {
$allowed_origin = $request_origin;
}
// print needed allowed origins
header( "Access-Control-Allow-Origin: {$allowed_origin}" );
header( 'Access-Control-Allow-Credentials: true' );
header( 'Access-Control-Allow-Methods: GET, POST, OPTIONS' );
// if this is a preflight request
if (
isset( $_SERVER['REQUEST_METHOD'] )
&& $_SERVER['REQUEST_METHOD'] === 'OPTIONS'
) {
// need preflight here
header( 'Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept' );
// add cache control for preflight cache
// @link https://httptoolkit.tech/blog/cache-your-cors/
header( 'Access-Control-Max-Age: 86400' );
header( 'Cache-Control: public, max-age=86400' );
header( 'Vary: origin' );
// just exit and CORS request will be okay
// NOTE: We are exiting only when the OPTIONS preflight request is made
// because the pre-flight only checks for response header and HTTP status code.
exit( 0 );
}
// get data from the database
$data = get_option( 'acme_preflight_data', null );
// send JSON response
header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
echo json_encode( $data );
// die to prevent further output
die();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment