如何使用 PHP 检查请求是否是 AJAX 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18260537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if the request is an AJAX request with PHP
提问by BackSlash
I would like to check server-side if a request to my php page is an ajax request or not.
我想检查服务器端对我的 php 页面的请求是否是 ajax 请求。
I saw two ways to do this:
我看到了两种方法来做到这一点:
First way: sending a GET
parameter in the request which tells the page that this is an AJAX request (=mypage.php?ajax
)
第一种方式:GET
在请求中发送一个参数,告诉页面这是一个 AJAX 请求 (= mypage.php?ajax
)
mypage.php:
我的页面.php:
if(isset($_GET['ajax'])) {
//this is an ajax request, process data here.
}
Second way: set a header to the xmlHttpRequest
:
第二种方式:将标题设置为xmlHttpRequest
:
client-side js:
客户端js:
xmlHttpRequestObject.open(“GET”,url,true);
xmlHttpRequestObject.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
mypage.php:
我的页面.php:
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) {
//request is 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 请求?
采纳答案by Wayne Whitty
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 发出的。您永远不能相信来自客户端的数据。您可以使用几种不同的方法,但可以通过欺骗轻松克服它们。
回答by Volodymyr
Here is the tutorialof achieving the result.
这是实现结果的教程。
Example:
例子:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
exit;
}
continue;
This checks if the
HTTP_X_REQUESTED_WITH
parameter is not empty and if it's equal toxmlhttprequest
, then it will exit from the script.
这会检查
HTTP_X_REQUESTED_WITH
参数是否不为空,如果它等于xmlhttprequest
,则它将退出脚本。
回答by GovCoder
Set a session variable for every page on your site (actual pages not includes or rpcs) that contains the current page name, then in your Ajax call pass a nonce salted with the $_SERVER['SCRIPT_NAME'];
为站点上包含当前页面名称的每个页面(实际页面不包括或 rpcs)设置一个会话变量,然后在您的 Ajax 调用中传递一个用 $_SERVER['SCRIPT_NAME'];
<?php
function create_nonce($optional_salt='')
{
return hash_hmac('sha256', session_id().$optional_salt, date("YmdG").'someSalt'.$_SERVER['REMOTE_ADDR']);
}
$_SESSION['current_page'] = $_SERVER['SCRIPT_NAME'];
?>
<form>
<input name="formNonce" id="formNonce" type="hidden" value="<?=create_nonce($_SERVER['SCRIPT_NAME']);?>">
<label class="form-group">
Login<br />
<input name="userName" id="userName" type="text" />
</label>
<label class="form-group">
Password<br />
<input name="userPassword" id="userPassword" type="password" />
</label>
<button type="button" class="btnLogin">Sign in</button>
</form>
<script type="text/javascript">
$("form.login button").on("click", function() {
authorize($("#userName").val(),$("#userPassword").val(),$("#formNonce").val());
});
function authorize (authUser, authPassword, authNonce) {
$.ajax({
type: "POST",
url: "/inc/rpc.php",
dataType: "json",
data: "userID="+authUser+"&password="+authPassword+"&nonce="+authNonce
})
.success(function( msg ) {
//some successful stuff
});
}
</script>
Then in the rpc you are calling test the nonce you passed, if it is good then odds are pretty great that your rpc was legitimately called:
然后在 rpc 中,您调用 test 您通过的随机数,如果它是好的,那么您的 rpc 被合法调用的可能性非常大:
<?php
function check_nonce($nonce, $optional_salt='')
{
$lasthour = date("G")-1<0 ? date('Ymd').'23' : date("YmdG")-1;
if (hash_hmac('sha256', session_id().$optional_salt, date("YmdG").'someSalt'.$_SERVER['REMOTE_ADDR']) == $nonce ||
hash_hmac('sha256', session_id().$optional_salt, $lasthour.'someSalt'.$_SERVER['REMOTE_ADDR']) == $nonce)
{
return true;
} else {
return false;
}
}
$ret = array();
header('Content-Type: application/json');
if (check_nonce($_POST['nonce'], $_SESSION['current_page']))
{
$ret['nonce_check'] = 'passed';
} else {
$ret['nonce_check'] = 'failed';
}
echo json_encode($ret);
exit;
?>
edit: FYI the way I have it set the nonce is only good for an hour and change, so if they have not refreshed the page doing the ajax call in the last hour or 2 the ajax request will fail.
编辑:仅供参考,我设置随机数的方式仅适用于一个小时并更改,因此如果他们在过去一小时或 2 小时内没有刷新执行 ajax 调用的页面,ajax 请求将失败。
回答by Emeszenes
From PHP 7 with null coalescing operator it will be shorter:
从带有空合并运算符的 PHP 7 开始,它会更短:
$is_ajax = 'xmlhttprequest' == strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' );
回答by Nanhe Kumar
This function is using in yii framework for ajax call check.
此函数在 yii 框架中用于 ajax 调用检查。
public function isAjax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
}
回答by revoke
$headers = apache_request_headers();
$is_ajax = (isset($headers['X-Requested-With']) && $headers['X-Requested-With'] == 'XMLHttpRequest');
回答by Sani Kamal
Try below code snippet
试试下面的代码片段
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
/* This is one ajax call */
}
回答by Static Cast
You could try using a $_SESSION
variable to make sure that a request was made from a browser. Otherwise, you could have the request sent through a database or file [server-side].
您可以尝试使用$_SESSION
变量来确保请求是从浏览器发出的。否则,您可以通过数据库或文件 [服务器端] 发送请求。