gpt4 book ai didi

php - 如何使用 PHP 检查请求是否是 AJAX 请求

转载 作者:IT王子 更新时间:2023-10-28 23:59:28 24 4
gpt4 key购买 nike

我想检查服务器端对我的 php 页面的请求是否是 ajax 请求。

我看到了两种方法:

第一种方式:在请求中发送一个 GET 参数,告诉页面这是一个 AJAX 请求 (=mypage.php?ajax)

mypage.php:

if(isset($_GET['ajax'])) {
//this is an ajax request, process data here.
}

第二种方式:给xmlHttpRequest设置一个header:

客户端js:

xmlHttpRequestObject.open(“GET”,url,true);
xmlHttpRequestObject.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

mypage.php:

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) {
//request is ajax
}

事实上,这两种方式很容易被黑客入侵,因此检查我是否收到这样的 AJAX 请求并不安全。

如何检查我是否收到 AJAX 请求?

最佳答案

示例来自 archived tutorial :

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 to xmlhttprequest, then it will exit from the script.

关于php - 如何使用 PHP 检查请求是否是 AJAX 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18260537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com