Prevent direct access to a PHP page

前端 未结 10 1943
说谎
说谎 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:10

    There is no way of guaranteeing that they're accessing it through AJAX. Both direct access and AJAX access come from the client, so it can easily be faked.

    Why do you want to do this anyways?

    If it's because the PHP code isn't very secure, make the PHP code more secure. (For example, if your AJAX passes the user id to the PHP file, write code in the PHP file to make sure that is the correct user id.)

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

    As others have said, Ajax request can be emulated be creating the proper headers. If you want to have a basic check to see if the request is an Ajax request you can use:

     if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
         //Request identified as ajax request
     }
    

    However you should never base your security on this check. It will eliminate direct accesses to the page if that is what you need.

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

    This definitely isn't useful for securing something.. but I think this could be of use if you wanted to have say a php page that generated a whole page if the page was not requested by ajax but only generate the part that you needed returned when ajax was used.. This would allow you to make your site non ajax friendly so if say they click on a link and it's supposed to load a box of comments but they don't have ajax it still sends them to the page that is then generated as a whole page displaying the comments.

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

    COOKIES are not secure... try the $_SESSION. That's pretty much one of the few things that you can actually rely on cross-page that can't be spoofed. Because, of course, it essentially never leaves your control.

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

    thanks, albeit I use

    define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
    
    if(IS_AJAX) {
        //Request identified as ajax request
    }
    

    cheers!

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

    Not sure about this, but possibly check for a referrer header? i think if someone manually typed in your url, it wouldn't have a referrer header, while AJAX calls do (at least in the quickly test I just did on my system).

    It's a bad way of checking though. Referrer can be blank for a lot of reasons. Are you trying to stop people from using your web service as a public service or something?

    After reading your edit comments, if the forms will be loaded via ajax calls, than you could check window.location to see if the url is your ajax form's url. if it is, go to the right page via document.location

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