如何使用PHP获取请求的来源? [英] How I can get origin of request with PHP?

查看:720
本文介绍了如何使用PHP获取请求的来源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有人将XHR请求从some-client.com发送到some-rest.com,我想使用PHP获取请求的来源(域名,而不是客户端ip ).

If someone send XHR request from some-client.com to some-rest.com, I want get origin(domain name, not client ip) of the request with PHP.

可能的解决方案:

  • 也许我可以使用$_SERVER['HTTP_ORIGIN'],但是我不知道这是否是标准.
  • 我看到了另一个标头,例如$_SERVER['HTTP_HOST']$_SERVER['SERVER_NAME'],但是在某些情况下,这将返回真实的hostname而不是真实的domain.
  • 然后$_SERVER['REMOTE_ADDR']给出客户端IP.
  • Maybe I can use $_SERVER['HTTP_ORIGIN'] but I don't know if it is a standard.
  • I see another header like $_SERVER['HTTP_HOST'] or $_SERVER['SERVER_NAME'], but some cases this return the real hostname and not the real domain.
  • And $_SERVER['REMOTE_ADDR'] gives the client IP.

用PHP获取域名之类的请求的正确方法是什么?

Whats is the correct way to get origin of request like a domain name with PHP?

谢谢!

推荐答案

根据文章

According to the article HTTP access control (CORS) by MDN:

必须将所有请求都设置为Origin标头,才能在CORS(跨源资源共享)机制下正常工作.

All requests must be set Origin header to work correctly under CORS(Cross-origin resource sharing) mechanism.

"来源"请求标头是 RFC 6454的一部分将其描述为CORS机制的一部分,并根据MDN与所有浏览器兼容.

The "Origin" request header is part of RFC 6454 and describes it as part of CORS mechanism and is compatible with all browsers according to MDN.

MDN描述:

Origin请求标头指示提取的来源.它 不包含任何路径信息,仅包含服务器名称.它是 与CORS请求以及POST请求一起发送.相似 到Referer标头,但与该标头不同,它没有披露 整个路径.

The Origin request header indicates where a fetch originates from. It doesn't include any path information, but only the server name. It is sent with CORS requests, as well as with POST requests. It is similar to the Referer header, but, unlike this header, it doesn't disclose the whole path.

来源: https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Origin

MDN示例:

因此,要使用PHP获取XHR请求的来源,您可以使用:

$_SERVER['HTTP_ORIGIN'] 

而且,在直接请求的情况下,您可以将 HTTP_REFERERREMOTE_ADDR组合在一起,例如:

And, in the case of a direct request, you can combine HTTP_REFERER and REMOTE_ADDR like:

if (array_key_exists('HTTP_REFERER', $_SERVER)) {
    $origin = $_SERVER['HTTP_REFERER'];
} else {
    $origin = $_SERVER['REMOTE_ADDR'];
}

因此,可能的最终解决方案是:

if (array_key_exists('HTTP_ORIGIN', $_SERVER)) {
    $origin = $_SERVER['HTTP_ORIGIN'];
}
else if (array_key_exists('HTTP_REFERER', $_SERVER)) {
    $origin = $_SERVER['HTTP_REFERER'];
} else {
    $origin = $_SERVER['REMOTE_ADDR'];
}

MDN是 Mozilla开发人员网络.

非常感谢@ trine,@ waseem-bashir,@ p0lt10n和其他人的帮助.

Thanks a lot for help @trine, @waseem-bashir, @p0lt10n, and others persons.

这篇关于如何使用PHP获取请求的来源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆