How to check if a request if coming from the same server or different server?

后端 未结 4 1952
北海茫月
北海茫月 2020-11-29 03:03

How can I check whether a request being received is sent from the same server??

Say, I\'ve my domain at www.domain.com. Now I\'ve php processing files which will pro

相关标签:
4条回答
  • 2020-11-29 03:24

    this will check if there is a referer, then it will compare it with current domain, if different then it is from outside referer

    if ((isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']))) {
    if (strtolower(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST)) != strtolower($_SERVER['HTTP_HOST'])) {
    // referer not from the same domain
    }
    }
    
    0 讨论(0)
  • 2020-11-29 03:43

    I know this is an old thread, but some one else can probably find it relevant.

    The answer is: Yes you can. But it depends if your Apache/nginx server is set to populate the $_SERVER variable with the required information. Most the server are, so probably you can use this approach.

    What you need to do is to extract the HTTP_REFERER from the $_SERVER variable and compare with your domain.

    <?php
    function requestedByTheSameDomain() {
        $myDomain       = $_SERVER['SCRIPT_URI'];
        $requestsSource = $_SERVER['HTTP_REFERER'];
    
        return parse_url($myDomain, PHP_URL_HOST) === parse_url($requestsSource, PHP_URL_HOST);
    }
    
    0 讨论(0)
  • 2020-11-29 03:44

    With curl I can set the REFERER to be 'www.domain.com', and call the form url (at www.domain.com) from my server (at www.mrhacker.com), but $_SERVER['HTTP_REFERER'] will give the value of www.domain.com

    (Almost) Anything coming from the client can be spoofed! I say almost, because the average Joe cannot spoof IP address, you can only send via proxy.

    0 讨论(0)
  • 2020-11-29 03:46

    Basically : you cannot.
    With the HTTP protocol, each request is independent from the others.


    A first idea would be to check the Referer HTTP header, but note that :

    • It can be faked (it's sent by the browser)
    • It is not always present.

    So : not a reliable solution.


    A possible, and far better than the Referer idea, solution could be to use a nonce :

    • When displaying the form, put a hidden input field in it, containing a random value
    • At the same time, store that random value into the session that correspond to the user.
    • When the form is submitted, check that the hidden field has the same value as the one that's stored in session.

    If those two values are not the same, refuse to use the submitted data.

    Note : this idea is often used to help fight against CSRF -- and integrated in the "Form" component of some Frameworks (Zend Framework, for instance).

    0 讨论(0)
提交回复
热议问题