Prevent external access to PHP scripts but allow AJAX

前端 未结 4 1447
挽巷
挽巷 2021-01-22 20:06

I\'ve read a lot about .htaccess rules, checking headers, using encryption etc.. but I haven\'t found exactly the answer I\'m after. I know that assuming the server is set up ri

相关标签:
4条回答
  • 2021-01-22 20:13

    There is NO way absolutely to safely/reliably identify which part of the browser the request comes from -- address bar, AJAX. There's a way to identify what is sending though browser/curl/etc via User-Agent header (but not reliably)

    A quick but a lot less reliable solution would be to check for the following header. Most browsers attach it with AJAX calls. Be sure to thoroughly look into it, and implement.

    X-Requested-With: XMLHttpRequest
    

    NOTE: Do not trust the client if the resource is cruicial. You are better off implementing some other means of access filtering. Remember, any one can fake headers!

    0 讨论(0)
  • 2021-01-22 20:20

    Try to catch if isset SERVER['HTTP_ORIGIN'] from the POST access, it must be identical to your domain. If so, then the POST is generated by yourselft website and it's safe to process it.

    0 讨论(0)
  • 2021-01-22 20:24

    You can check whether the request isn't an Ajax request and forbid it, but it's not really safe due to the fact that the headers can be manipulated.

    What you can do is to block every IP except the IP which is allowed to access those files.

    What can do either is do implement a kind of authentication, where external applications have to send credentials to your script and the scripts checks if the client is valid.

    Many ways, but they're all not really the best ways to achieve maximum security.

    0 讨论(0)
  • 2021-01-22 20:26

    I do not know definitely. However – indirectly, you can do this. Pass a unique and constantly changing parameter (GET or POST) that only you have access to as proof of the origin. If the request lacks this unique variable, then its not from you. Think outside the box on this one. Could be anything you want, here are some ideas.

    1) pass the result of a mathematical equation as proof of origin. Something that you can programmatically predict, yet not obvious to prying header hackers. i.e cos($dayOfYear) or even better base64_encode(base64_encode(cos($dayOfYear))).

    2) store a unique key in a database that changes every time someone access the page. Then pass that key along with the request, and do some checks on the end page, if they dont match up to the database key, you've found the peeping tom. (note there will be logic involved for making sure the key hasn't changed in between transmission of requests)

    etc..

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