简体   繁体   English

阻止直接访问PHP文件,仅允许本地javascript访问它

[英]block direct access to PHP file and only allow local javascript to access it

I need a way to block all access to a php file but to allow a javascript file that send xmlhttp request to it. 我需要一种方法来阻止对php文件的所有访问,但要允许向其发送xmlhttp请求的javascript文件。 that js file is hosted on my server and must stay on my server for it to work 该js文件托管在我的服务器上,并且必须保留在我的服务器上才能正常工作

I have the following 我有以下

header('Access-Control-Allow-Origin: *');

but that allows anyone to access it. 但是,任何人都可以访问它。

Well, I don't think this would be possible. 好吧,我认为这不可能。 Anyone can make a request to your server but your server chooses who to respond to and how to respond to a request. 任何人都可以向您的服务器发出请求,但是您的服务器会选择响应谁以及如何响应请求。 Now, if you want only your JS to be responded to by your server, then you will have to inform the server at the time of making an HTTP request from your JS. 现在,如果您只希望服务器响应您的JS,那么您必须在从JS发出HTTP请求时通知服务器。 That cannot be done without exposing your Javscript file's identity on the basis of which your JS can be identified by the server. 如果不公开Javscript文件的身份,服务器无法识别JS,就无法这样做。 But anyone can open your JS and read it and figure out how you are making the request and use the same thing. 但是任何人都可以打开您的JS并阅读它,然后弄清楚您是如何发出请求的并且使用相同的东西。

One possible solution could be, use header('Access-Control-Allow-Origin: *') to allow everyone to make a request to your server but at the server's end, keep a list of allowed domains/origins in a database on your server who may use or are going to use your JS file on their website. 一种可能的解决方案是,使用标头('Access-Control-Allow-Origin:*')允许每个人向您的服务器发出请求,但在服务器端,在您的数据库中保留允许的域/来源列表可能会或打算在其网站上使用您的JS文件的服务器。 Based on the AJAX request that you get, you check from your database that if the origin of the request is allowed or not and respond accordingly. 根据收到的AJAX请求,从数据库中检查请求的来源是否被允许,并做出相应的响应。 Now, if someone tries to request your PHP file by any other means than your JS, on the basis of the data in your DB you can reject the request or accept the request. 现在,如果有人尝试通过您的JS以外的任何其他方式请求您的PHP文件,则根据您数据库中的数据,您可以拒绝该请求或接受该请求。 If an allowed user/website does this, then they will be knowingly messing around with their own data. 如果允许的用户/网站执行此操作,那么他们将有意识地摆弄自己的数据。

Try this: 尝试这个:

if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) <> 'xmlhttprequest') 
{ 
    die('direct access is not allowed'); 
} 

Also, you can always check referrer like $_SERVER['HTTP_REFERER'] to be sure that only your script from your domain can access it. 另外,您始终可以检查诸如$ _SERVER ['HTTP_REFERER']之类的引荐来源网址,以确保只有您域中的脚本才能访问它。

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

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