防止直接访问 ajax 函数调用的文件 [英] Prevent Direct Access To File Called By ajax Function

查看:41
本文介绍了防止直接访问 ajax 函数调用的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在像这样从 ajax 调用 php 代码:

I'm calling the php code from ajax like this:

ajaxRequest.open("GET", "func.php" + queryString, true);

由于它是一个 get 请求,任何人都可以通过简单地检查标题来看到它.传递的数据并不敏感,但可能会被滥用,因为获取参数名称也很简单.

Since it's a get request anyone can see it by simply examining the headers. The data being passed is not sensitive, but it could potentially be abused since it is also trivial to get the parameter names.

如何防止直接访问 http://mysite/func.php 但允许我的 ajax 页面访问给它吗?

How do I prevent direct access to http://mysite/func.php yet allow my ajax page access to it?

我也尝试过发布在这里 但它对我不起作用 - 总是收到未允许直接访问"消息.

Also I have tried the solution posted here but its doesn't work for me - always get the 'Direct access not premitted' message.

推荐答案

大多数 Ajax 请求/框架都应该设置这个特定的标头,您可以使用它来过滤 Ajax 与非 ajax 请求.我用它来帮助确定大量项目中的响应类型 (json/html):

Most Ajax requests/frameworks should set this particular header that you can use to filter Ajax v Non-ajax requests. I use this to help determine response type (json/html) in plenty of projects:

if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) )
{
    // allow access....
} else {
    // ignore....
} 

您可以在自己的 Ajax 请求中使用以下 javascript 代码自行添加:

edit: You can add this yourself in your own Ajax requests with the following in your javascript code:

var xhrobj = new XMLHttpRequest();
xhrobj.setRequestHeader("X-Requested-With", "XMLHttpRequest"); 

这篇关于防止直接访问 ajax 函数调用的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆