diff --git a/packages/playground/php-cors-proxy/cors-proxy-functions.php b/packages/playground/php-cors-proxy/cors-proxy-functions.php index 1db0a4faf4..338c51edc7 100644 --- a/packages/playground/php-cors-proxy/cors-proxy-functions.php +++ b/packages/playground/php-cors-proxy/cors-proxy-functions.php @@ -354,3 +354,30 @@ function rewrite_relative_redirect( } return $proxy_absolute_url . $redirect_location; } + +/** + * Answers whether CORS is allowed for the specified origin. + */ +function should_respond_with_cors_headers($host, $origin) { + if (empty($origin)) { + return false; + } + + $is_request_from_playground_web_app = $origin === 'https://playground.wordpress.net'; + $not_hosted_with_playground_web_app = $host !== 'playground.wordpress.net'; + if ( + $is_request_from_playground_web_app && + $not_hosted_with_playground_web_app + ) { + return true; + } + + $origin_host = parse_url($origin, PHP_URL_HOST); + $is_local_origin = in_array( + $origin_host, + array('localhost', '127.0.0.1'), + true + ); + + return $is_local_origin; +} diff --git a/packages/playground/php-cors-proxy/cors-proxy.php b/packages/playground/php-cors-proxy/cors-proxy.php index 9fb854f391..04b2b483b5 100644 --- a/packages/playground/php-cors-proxy/cors-proxy.php +++ b/packages/playground/php-cors-proxy/cors-proxy.php @@ -13,6 +13,16 @@ require_once $config_file; } +$server_host = $_SERVER['HTTP_HOST'] ?? ''; +$origin = $_SERVER['HTTP_ORIGIN'] ?? ''; + +if (should_respond_with_cors_headers($server_host, $origin)) { + header('Access-Control-Allow-Origin: ' . $origin); + header('Access-Control-Allow-Credentials: true'); + header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); + header('Access-Control-Allow-Headers: Authorization, Content-Type'); +} + if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { header("Allow: GET, POST, OPTIONS"); exit;