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

梦想与她 提交于 2019-12-22 01:51:07

问题


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?


回答1:


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();



回答2:


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: *");


来源:https://stackoverflow.com/questions/12630589/add-access-control-allow-origin-to-header-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!