PHP 要判斷 Request 是 AJAX 發送過來(吐 JSON), 還是一般正常的網頁瀏覽(吐 HTML), 要怎麼做?
PHP 判斷 AJAX Request (XHRs) 的方法
可以由 HTTP Header (HTTP_X_REQUESTED_WITH = xmlhttprequest) 來判斷是否是 AJAX 的 Request.
<?php function is_ajax() { return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'); } ?>
模擬測試
透過 wget 模擬測試 (Simulate) XHRs 的 Request
- wget --header="X-Requested-With: XMLHttpRequest" http://example.com/ # 存檔
- wget --header="X-Requested-With: XMLHttpRequest" -qO- http://example.com/ # 將結果 直接印在 Terminal.
透過 curl
- curl -H "X-Requested-With: XMLHttpRequest" ...
-
<?php $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Requested-With: XMLHttpRequest")); $result = curl_exec($ch); curl_close($ch); ?>