问题描述
我想检查服务器端对我的 php 页面的请求是否是 ajax 请求.
I would like to check server-side if a request to my php page is an ajax request or not.
我看到了两种方法:
第一种方式:在请求中发送一个 GET
参数,告诉页面这是一个 AJAX 请求 (=mypage.php?ajax
)
First way: sending a GET
parameter in the request which tells the page that this is an AJAX request (=mypage.php?ajax
)
mypage.php:
mypage.php:
if(isset($_GET['ajax'])) {
//this is an ajax request, process data here.
}
第二种方式:给xmlHttpRequest
设置一个header:
Second way: set a header to the xmlHttpRequest
:
客户端js:
xmlHttpRequestObject.open("GET",url,true);
xmlHttpRequestObject.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
mypage.php:
mypage.php:
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) {
//request is ajax
}
事实上,这两种方式很容易被黑客入侵,所以检查我是否收到这样的 AJAX 请求是不安全的.
The fact is, those two ways of doing it can easily be hacked, so it's not secure to check if i get an AJAX request like this.
如何检查我是否收到了 AJAX 请求?
How can i check if i'm receiving an AJAX request?
推荐答案
没有确定的方法可以知道请求是通过 Ajax 发出的.您永远不能相信来自客户端的数据.您可以使用多种不同的方法,但可以通过欺骗轻松克服它们.
There is no sure-fire way of knowing that a request was made via Ajax. You can never trust data coming from the client. You could use a couple of different methods but they can be easily overcome by spoofing.
这篇关于如何使用 PHP 检查请求是否是 AJAX 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!