Prevent direct access to a PHP page

前端 未结 10 1944
说谎
说谎 2020-12-01 09:34

How do I prevent my users from accessing directly pages meant for ajax calls only?

Passing a key during ajax call seems like a solution, whereas access without the k

相关标签:
10条回答
  • 2020-12-01 10:31

    Pass your direct requests through index.php and your ajax requests through ajax.php and then dont let the user browse to any other source file directly - make sure that index.php and ajax.php have the appropriate logic to include the code they need.

    0 讨论(0)
  • 2020-12-01 10:32

    It sounds like you might be going about things the wrong way. An AJAX call is just like a standard page request, only by convention the response is not intended for display to the user.

    It is, however, still a client request, and so you must be happy for the client to be able to see the response. Obfuscating access using a "key" in this way only serves to complicate things.

    I'd actually say the "curse" of view source is a small weapon in the fight against security through obscurity.

    So what's your reason for wanting to do this?

    0 讨论(0)
  • 2020-12-01 10:32

    If the browser will call your page, either by normal request or ajax, then someone can call it manually. There really isn't a well defined difference between normal and ajax requests as far as the server-client communication goes.

    Common case is to pass a header to the server that says "this request was done by ajax". If you're using Prototype, it automatically sets the http header "X-Requested-With" to "XMLHttpRequest" and also some other headers including the prototype version. (See more at http://www.prototypejs.org/api/ajax/options at "requestHeaders" )

    Add: In case you're using another AJAX library you can probably add your own header. This is useful for knowing what type of request it was on the server side, and for avoiding simple cases when an ajax page would be requested in the browser. It does not protect your request from everyone because you can't.

    0 讨论(0)
  • 2020-12-01 10:36

    In the javascript file that calls the script:

    var url = "http://website.com/ajax.php?say=hello+world";
    xmlHttp.open("GET", url, true);
    xmlHttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    

    then in the php file ajax.php:

    if($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
        header("Location: http://website.com");
        die();
    }
    

    Geeks can still call the ajax.php script by forging the header but the rest of my script requires sessions so execution ends when no valid session is detected. I needed this to work in order to redirect people with expired hybridauth sessions to the main site in order to login again because they ended up being redirected to the ajax script.

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