Add Access-Control-Allow-Origin to header in PHP
Posted
by
SANDeveloper
on Stack Overflow
See other posts from Stack Overflow
or by SANDeveloper
Published on 2012-09-27T21:53:33Z
Indexed on
2012/10/16
23:01 UTC
Read the original article
Hit count: 270
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:
- Write a PHP script to handle image requests
- Image requests would be sent through the query string as a url parameter
The PHP Script will:
- Call the web service with the query string url
- Fetch the image response (web service returns a content-type:image response)
- Add the CORS header (Add Access-Control-Allow-Origin) to the response
- 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:
- Is the approach good enough?
- 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?
Managed to get it working:
$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
$headers = curl_getinfo($ch);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
header('Content-Type: image/jpeg');
header("Access-Control-Allow-Origin: *");
// header("Expires: Sat, 26 Jul 2017 05:00:00 GMT");
//close connection
curl_close($ch);
flush();
© Stack Overflow or respective owner