如何使用 PHP 获取请求的来源?

2022-01-05 00:00:00 request php ajax apache cross-domain

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

可能的解决方案:

  • 也许我可以使用 $_SERVER['HTTP_ORIGIN'] 但我不知道它是否是标准.
  • 我看到另一个标头,如 $_SERVER['HTTP_HOST']$_SERVER['SERVER_NAME'],但在某些情况下,这会返回真正的 hostname 而不是真正的 domain.
  • 并且 $_SERVER['REMOTE_ADDR'] 提供客户端 IP.

使用 PHP 获取请求来源(如域名)的正确方法是什么?

谢谢!

解决方案

根据文章

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

$_SERVER['HTTP_ORIGIN']

而且,在直接请求的情况下,您可以结合 HTTP_REFERERREMOTE_ADDR 像:

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

所以,可能的最终解决方案是:

if (array_key_exists('HTTP_ORIGIN', $_SERVER)) {$origin = $_SERVER['HTTP_ORIGIN'];}否则 if (array_key_exists('HTTP_REFERER', $_SERVER)) {$origin = $_SERVER['HTTP_REFERER'];} 别的 {$origin = $_SERVER['REMOTE_ADDR'];}

MDN 是 Mozilla 开发者网络.

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

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.

The possible solutions:

  • 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.

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

Thanks!

解决方案

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

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

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.

Description by MDN:

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.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin

Example by MDN:

So, to get origin of the XHR request with PHP you can use:

$_SERVER['HTTP_ORIGIN'] 

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'];
}

So, the possible final solution is:

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 is Mozilla Developer Network.

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

相关文章