如何检查是否该请求是一个AJAX请求与PHP [英] How to check if the request is an AJAX request with PHP
问题描述
我想检查服务器端是否要求我的PHP页面是一个Ajax请求。
I would like to check server-side if a request to my php page is an ajax request or not.
我看到了两种方法可以做到这一点:
I saw two ways to do this:
第一种方式:发送中告诉页,这是一个Ajax请求(= mypage.php AJAX <请求中的
GET
参数? / code>)
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.
}
方式二:设置一个标题为 xmlHtt prequest
:
客户端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.
这篇关于如何检查是否该请求是一个AJAX请求与PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!