主流 JavaScript 庫(jQuery、Axios、Fetch API 等)在發送 AJAX 請求時,會自動加入標頭:
X-Requested-With: XMLHttpRequest
PHP 透過 $_SERVER['HTTP_X_REQUESTED_WITH'] 即可檢測。
<?php
/**
* 判斷是否為 AJAX 請求
* @return bool
*/
function isAjax(): bool
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strcasecmp($_SERVER['HTTP_X_REQUESTED_WITH'], 'XMLHttpRequest') === 0;
}
// 使用範例
if (isAjax()) {
// 回傳 JSON
header('Content-Type: application/json');
echo json_encode(['status' => 'ok', 'data' => $data]);
exit;
}
// 非 AJAX:正常渲染頁面
include 'layout.php';
?>
<?php
class RequestDetector
{
public static function isAjax(): bool
{
return self::hasHeader('X-Requested-With', 'XMLHttpRequest');
}
public static function isApi(): bool
{
// API 請求通常帶 Accept: application/json 或自定義標頭
return self::hasHeader('Accept', 'application/json')
|| self::hasHeader('X-API-Key')
|| self::hasHeader('Authorization', 'Bearer ');
}
public static function isPjax(): bool
{
return self::hasHeader('X-PJAX');
}
public static function wantsJson(): bool
{
return self::isAjax()
|| self::isApi()
|| (isset($_SERVER['HTTP_ACCEPT'])
&& strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false);
}
private static function hasHeader(string $header, string $expectedValue = ''): bool
{
$serverKey = 'HTTP_' . strtoupper(str_replace('-', '_', $header));
if (!isset($_SERVER[$serverKey])) return false;
return $expectedValue === '' || stripos($_SERVER[$serverKey], $expectedValue) !== false;
}
}
// 統一回應格式
function respond($data, int $status = 200): never
{
http_response_code($status);
if (RequestDetector::wantsJson()) {
header('Content-Type: application/json');
echo json_encode($data, JSON_UNESCAPED_UNICODE);
} else {
// HTML 回應或重導向
echo $data['html'] ?? 'OK';
}
exit;
}
?>
$.ajax({
url: '/api/user',
// 預設會送 X-Requested-With: XMLHttpRequest
});
// 預設不送 X-Requested-With,需手動加入
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
// 或單次請求
axios.get('/api', { headers: { 'X-Requested-With': 'XMLHttpRequest' }});
fetch('/api', {
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'application/json'
}
});
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send();
| 問題 | 原因 | 解決 |
|---|---|---|
| isAjax() 回傳 false | 前端未送標頭(Axios/Fetch 預設不送) | 前端加入標頭,或改用 Accept 檢測 |
| 跨域請求無標頭 | CORS 預檢未允許自定義標頭 | 後端 Access-Control-Allow-Headers 加入 X-Requested-With |
| 反向代理吃掉標頭 | Nginx/Apache 未轉發 | proxy_set_header X-Requested-With $http_x_requested_with; |
| 偽造 AJAX 請求 | 攻擊者手動加標頭 | 不可單靠此標頭做權限控制,需配合 CSRF Token、JWT 等 |