[英]Cross-domain XMLHttpRequest, Access-Control-Allow-Origin header and $_SERVER['HTTP_ORIGIN']
I need a script to deliver information to requesting-pages hosted on different domains, through XMLHttpRequest.我需要一个脚本来通过 XMLHttpRequest 将信息传送到托管在不同域上的请求页面。 There are many questions and answers on the subject, but none of the ones I found fully answered my questions.
关于这个主题有很多问题和答案,但我发现没有一个能完全回答我的问题。
Searching on the net brought me to find out that I must allow these domains through headers like在网上搜索让我发现我必须通过标头允许这些域,例如
header("Access-Control-Allow-Origin: *");
or或者
header("Access-Control-Allow-Origin: http://example.com");
As I need more than one external domain, but still I find *
much too open, further researches brought me on solutions relying on server-side comparison of $_SERVER['HTTP_ORIGIN']
with authorized values.由于我需要多个外部域,但我仍然发现
*
太开放了,进一步的研究使我找到了依赖于$_SERVER['HTTP_ORIGIN']
与授权值的服务器端比较的解决方案。 (on StackOverflow: Access-Control-Allow-Origin Multiple Origin Domains? for instance) (在 StackOverflow: Access-Control-Allow-Origin Multiple Origin Domains?例如)
BUT I found no mention of $_SERVER['HTTP_ORIGIN']
in php manuel ( http://php.net/manual/fr/reserved.variables.server.php ) and my tests revealed that this entry isn't always set.但是我发现在 php 手册( http://php.net/manual/fr/reserved.variables.server.php )中没有提到
$_SERVER['HTTP_ORIGIN']
并且我的测试显示这个条目并不总是被设置。
So my questions are:所以我的问题是:
- when is the $_SERVER['HTTP_ORIGIN']
superglobal set? - 何时设置
$_SERVER['HTTP_ORIGIN']
超全局设置?
- is it reliable globally?... or client browser dependant? - 它在全球范围内可靠吗?...还是依赖于客户端浏览器?
It seems (but just empirically, from my tests / Firefox 34.0.5 & ios Safari) that it is only set when 'needed', ie when request actually comes from another domain.似乎(但仅凭经验,从我的测试/Firefox 34.0.5 和 ios Safari)它仅在“需要”时才设置,即当请求实际上来自另一个域时。
See short code extract hereunder to help understand the need请参阅下面的短代码摘录以帮助理解需求
- no header sent if $_SERVER['HTTP_ORIGIN']
not defined - 如果
$_SERVER['HTTP_ORIGIN']
未定义,则不发送标头
(assuming it's effectively not a cross domain call, there shouldn't be any problem), (假设它实际上不是跨域调用,应该没有任何问题),
- send "allow" header if defined and belonging to an array of accepted domains. - 如果已定义并属于一组接受域,则发送“允许”标头。
if(isset($_SERVER['HTTP_ORIGIN'])) {// in case of cross domain ajax call
$http_origin = $_SERVER['HTTP_ORIGIN'];
if(in_array($http_origin, $ajaxAllowedDomains))
{ header("Access-Control-Allow-Origin: $http_origin"); }
}
when is the
$_SERVER['HTTP_ORIGIN']
superglobal set?$_SERVER['HTTP_ORIGIN']
超全局设置是什么时候?
When the HTTP request includes an Origin
header.当 HTTP 请求包含
Origin
标头时。 Browsers will set one when making a cross-domain request with XMLHttpRequest.浏览器在使用 XMLHttpRequest 进行跨域请求时会设置一个。
is it reliable globally?
它在全球范围内可靠吗?
It is in situations where you might want to set CORS response headers.在您可能想要设置 CORS 响应标头的情况下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.