开发者

How to only allow calls to PHP scripts from files on my server?

开发者 https://www.devze.com 2023-03-01 05:42 出处:网络
For AJAX on my website, I make calls from a Javascript file to something.php?request=bla.I don\'t want the user to view the results of this request or even run the PHP file by typing in www.myurl.com/

For AJAX on my website, I make calls from a Javascript file to something.php?request=bla. I don't want the user to view the results of this request or even run the PHP file by typing in www.myurl.com/something.php?request=bla. I only want files on my server to be able to call PHP files. There are many things I have considered, such as secret values that get compared in the PHP scripts themselves, but that sounds too complicated for w开发者_StackOverflowhat I want. I am sure there is a simpler way.

How do I make it so that a PHP file can only be run if a script existing ON THE SERVER calls it? Users should not be able to run it using their address bar.


This is fundamentally impossible. Your Ajax request is always coming from the client.

You could in theory check for the HTTP_REFERER header, but as a security measure, this is completely useless. Every aspect of a request (Ajax or not) that comes from the client can be freely manipulated, including the referer field. It is trivial to fake an Ajax request that allegedly was started on your page.

It shouldn't be necessary for you to impose such a restriction in the first place: If you have a security system in place (like a login), that system's restrictions will (or should) apply to Ajax requests as well.

If you have Ajax requests that allow harmful actions (like deleting) without authentication, you will need to add authentication. There is no way you can limit those requests to a certain context or web site.


Use POST for all your AJAX calls, and reject all GET requests. That won't be perfect, but it will be good enough.


As workaround (only!) you can probe for the X-Requested-With: header. That differentiates real AJAX requests from address bar invocations. You cannot ensure the origin of the request with that.

if (stristr($_SERVER["HTTP_X_REQUESTED_WITH"], "XMLHttpRequest")) {

(You could inject some more obfuscation headers with your $.ajax() calls. But again, that's just making it more cumbersome to fake, not impossible.)

0

精彩评论

暂无评论...
验证码 换一张
取 消