在PHP 中, header()函數是一個非常重要的工具,用於向客戶端發送原始HTTP 報文頭。通過它,我們可以控制頁面的緩存、重定向、內容類型等。與此同時, headers_list()函數則可以幫助我們查看當前已經設置的所有HTTP 頭信息,這對於調試和理解程序行為非常有幫助。
本文將詳細介紹如何使用header()和headers_list() ,並通過代碼示例幫助你掌握它們的用法。
header()函數的基本語法如下:
header(string $header, bool $replace = true, int $response_code = 0): void
$header :要發送的header 內容,比如Content-Type: application/json 。
$replace :是否替換前面同名的header,默認為true 。
$response_code :可選參數,用於設置HTTP 響應狀態碼。
常見用法包括:
header('Location: https://m66.net/new-page.php');
exit;
這行代碼會讓瀏覽器重定向到https://m66.net/new-page.php 。
header('Content-Type: application/json');
echo json_encode(['status' => 'ok']);
這會告訴客戶端,接下來的內容是JSON 格式。
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
這些header 用於禁止緩存,確保用戶每次訪問都獲取最新內容。
有時候我們在代碼中多次調用header() ,但具體發送了哪些header 呢?這時headers_list()就派上用場了。
<?php
header('Content-Type: text/plain');
header('X-Custom-Header: CustomValue');
header('Location: https://m66.net/redirected');
$headers = headers_list();
echo "當前設置的 HTTP 頭:\n";
foreach ($headers as $h) {
echo $h . "\n";
}
?>
說明:
我們設置了三個header。
然後用headers_list()獲取到當前所有待發送的header,並逐行輸出。
運行這個腳本後,你會看到類似這樣的輸出:
Content-Type: text/plain
X-Custom-Header: CustomValue
Location: https://m66.net/redirected
請注意:
如果腳本已經輸出了內容(如echo ),再調用header()會導致“header already sent”錯誤。
所以,修改header 時應確保它們在任何輸出發生之前。
相關標籤:
header