SANDeveloper
SANDeveloper

Reputation: 570

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

I am trying to workaround CORS restriction on a WebGL application. I have a Web Service which resolves URL and returns images. Since this web service is not CORS enabled, I can't use the returned images as textures.

I was planning to:

  1. Write a PHP script to handle image requests
  2. Image requests would be sent through the query string as a url parameter

The PHP Script will:

  1. Call the web service with the query string url
  2. Fetch the image response (web service returns a content-type:image response)
  3. Add the CORS header (Add Access-Control-Allow-Origin) to the response
  4. Send the response to the browser

I tried to implement this using a variety of techniques including CURL, HTTPResponse, plain var_dump etc. but got stuck at some point in each.

So I have 2 questions:

  1. Is the approach good enough?
  2. Considering the approach is good enough:

I made the most progress with CURL. I could get the image header and data with:

$ch = curl_init();
$url = $_GET["url"];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:image/jpeg'));

//Execute request 
    $response = curl_exec($ch);

//get the default response headers 
    $headers = curl_getinfo($ch);

//close connection 
    curl_close($ch);

But this doesn't actually change set the response content-type to image/jpeg. It dumps the header + response into a new response of content-type text/html and display the header and the image BLOB data in the browser.

How do I get it to send the response in the format I want?

Upvotes: 14

Views: 58110

Answers (2)

Lukas Liesis
Lukas Liesis

Reputation: 26393

make sure that Apache (if you are using Apache) has mod_headers loaded before using all that stuff with headers.

(following tips works on Ubuntu, don't know about other distributions)

you can check list of loaded modules with

apache2ctl -M

to enable mod_headers you can use

a2enmod headers

of course after any changes in Apache you have to restart it:

/etc/init.d/apache2 restart

after this try adding this line to your .htaccess, or of course use php headers

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

PHP:

header("Access-Control-Allow-Origin: *");

Upvotes: 7

SANDeveloper
SANDeveloper

Reputation: 570

The simplest approach turned out to be the answer. Just had to insert the header before sending the response off.

    $ch = curl_init();
    $url = $_GET["url"];
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);

//Execute request 
    $response = curl_exec($ch);

//get the default response headers 
    header('Content-Type: image/jpeg');
    header("Access-Control-Allow-Origin: *");

//close connection 
    curl_close($ch);
    flush();

Upvotes: 15

Related Questions