Skip to content

Instantly share code, notes, and snippets.

@swashata
Created August 13, 2021 13:51

Revisions

  1. swashata created this gist Aug 13, 2021.
    56 changes: 56 additions & 0 deletions api.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    <?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();
    }