How I can get origin of request with PHP?

前端 未结 3 1159
盖世英雄少女心
盖世英雄少女心 2021-01-04 20:42

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 wi

3条回答
  •  青春惊慌失措
    2021-01-04 21:09

    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.

提交回复
热议问题