Add Access-Control-Allow-Origin to header in PHP

Add Access-Control-Allow-Origin to header in PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Add Access-Control-Allow-Origin to Header in PHP

Bypassing CORS restrictions to load external textures for a WebGL application is a common pattern, but implementing it correctly in PHP requires handling both binary data and HTTP headers with precision. The proposed architecture—using a PHP proxy to fetch an image from a non-CORS-enabled source and re-serving it with the appropriate headers—is a valid approach. However, the implementation details often trip up developers who are not accustomed to the specific behaviors of cURL regarding output buffering and header injection.

The core issue in the provided code snippet lies in how curl_exec interacts with PHP's default output stream and the explicit setting of CURLOPT_HEADER. By default, when you call curl_exec, PHP echoes the response body immediately if no output handling is configured. Furthermore, simply passing raw headers retrieved via curl_getinfo does not automatically inject them into your own response; you must explicitly set them using header().

To make this work, you need to disable cURL's automatic output and ensure that all binary data is captured in a variable rather than being streamed directly to the browser. The most reliable method involves setting CURLOPT_RETURNTRANSFER to true. This forces cURL to return the response as a string instead of printing it, allowing you full control over what gets sent back to the client.

Here is how to refactor the logic to correctly serve the image with CORS headers:

$url = $_GET['url'] ?? '';
$ch = curl_init();

// Configure cURL to return response as a string and handle binary data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Critical: prevent direct output
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Handle redirects if necessary
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Adjust based on security requirements

// Execute the request against the external service
$responseBody = curl_exec($ch);
$curlError = curl_error($ch);

if ($responseBody === false && $curlError !== '') {
    die('cURL Error: ' . $curlError);
}

curl_close($ch);

// Inject the CORS header before any output is sent
// Note: This allows requests from any origin. For production, restrict this to specific domains.
header('Access-Control-Allow-Origin: *'); 
header('Content-Type: image/jpeg', true); // The 'true' flag clears previous Content-Type headers

echo $responseBody;

The critical step here is ensuring that CURLOPT_RETURNTRANSFER is enabled before executing the request. Without it, PHP might attempt to send its own default headers (like Content-Type: text/html) or flush the output buffer prematurely, making it impossible to inject custom headers later. Additionally, using header($header, true) ensures that any previously set headers are cleared and replaced with your specific values, preventing conflicts.

One significant pitfall to consider is security. Setting Access-Control-Allow-Origin to * (wildcard) allows any website to request this image from your PHP script. If the external service returns sensitive data or if an attacker can manipulate the $url parameter in a cross-site scripting (XSS) context, this could expose them to the same origin policy violations you are trying to solve. Ideally, you should restrict this header to a specific list of trusted origins rather than using a wildcard, especially when dealing with user-controlled URLs.

Furthermore, always validate the $url parameter to ensure it points to a safe domain before making the outbound request. If the upstream service returns an error status code (like 403 or 500), you should return those status codes as well so the browser can handle them correctly, rather than echoing raw HTML error pages which might break your WebGL texture loader.

If you are building a larger application stack, frameworks like Laravel provide robust helpers for managing headers and output. For instance, in a Laravel controller, you would simply use the Response facade to set these headers cleanly without worrying about manual cURL configuration or output buffering issues that plague raw PHP scripts. This separation of concerns keeps your image proxy logic isolated from your main application logic.

Our network