简体   繁体   English

如何仅允许从服务器上的文件调用PHP脚本?

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

For AJAX on my website, I make calls from a Javascript file to something.php?request=bla. 对于我网站上的AJAX,我从Javascript文件向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. 我不希望用户查看此请求的结果,甚至不希望通过输入www.myurl.com/something.php?request=bla来运行PHP文件。 I only want files on my server to be able to call PHP files. 我只希望服务器上的文件能够调用PHP文件。 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 what I want. 我考虑了很多事情,例如在PHP脚本本身中比较了秘密值,但这听起来太复杂了。 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? 我如何使它仅在服务器上存在的脚本调用PHP文件的情况下才能运行? 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. 您的Ajax请求始终来自客户端。

You could in theory check for the HTTP_REFERER header, but as a security measure, this is completely useless. 从理论上讲,您可以检查HTTP_REFERER标头,但是作为安全措施,这完全没有用。 Every aspect of a request (Ajax or not) that comes from the client can be freely manipulated, including the referer field. 来自客户端的请求的各个方面(无论是否为Ajax)都可以自由操纵,包括引用字段。 It is trivial to fake an Ajax request that allegedly was started on your page. 伪造据称已在您的页面上启动的Ajax请求很简单。

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. 首先,您没有必要施加这样的限制:如果您已经建立了安全系统(例如登录名),那么该系统的限制也将(或应该)应用于Ajax请求。

If you have Ajax requests that allow harmful actions (like deleting) without authentication, you will need to add authentication. 如果您的Ajax请求允许未经身份验证的有害操作(例如删除),则需要添加身份验证。 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. 对所有AJAX调用使用POST,并拒绝所有GET请求。 That won't be perfect, but it will be good enough. 那不是完美的,但足够了。

As workaround (only!) you can probe for the X-Requested-With: header. 作为解决方法 (仅!),您可以探测X-Requested-With:标头。 That differentiates real AJAX requests from address bar invocations. 这将实际的AJAX请求与地址栏调用区分开。 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.) (您可以在$ .ajax()调用中注入一些混淆的标头。但是,这再次使假冒变得更加麻烦,并非没有可能。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM