在PHP中将Access-Control-Allow-Origin添加到标头 [英] Add Access-Control-Allow-Origin to header in PHP
问题描述
我试图解决一个WebGL应用程序的CORS限制。我有一个Web服务,它解析URL并返回图像。由于此网络服务未启用CORS,因此我无法将返回的图片用作纹理。
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.
我计划:
- 编写一个PHP脚本来处理图像请求
- 图像请求将通过查询字符串作为url发送
参数 -
- Write a PHP script to handle image requests
- Image requests would be sent through the query string as a url parameter
PHP脚本将:
- 获取图片响应(网络服务返回内容类型:图片响应)
- 添加CORS标头添加Access-Control-Allow-Origin)到
响应 - 将响应发送到浏览器
- 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
我试图使用各种技术实现这一点,包括CURL,HTTPResponse,plain var_dump等,但是在某些时候陷入困境。
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.
我有2个问题:
- 这种方法是否足够好?
- :
我用CURL取得了最大的进步。我可以得到图像头和数据:
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);
但实际上并没有将响应内容类型设置为image / jpeg。它将标题+响应转换为内容类型text / html的新响应,并在浏览器中显示标题和图片BLOB数据。
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.
如何获取
管理以使其正常工作:
$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();
推荐答案
最简单的方法是答案。只是在发送响应之前插入标头。
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();
这篇关于在PHP中将Access-Control-Allow-Origin添加到标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!