HTTP 函數允許您在輸出內容發送給瀏覽器之前,操作 Web 伺服器發送的 HTTP 標頭資訊。常用於設定 Cookie、重導向、快取控制、內容類型等。所有函數內建於 PHP 核心,無需安裝。
| 函數 | 說明 | PHP 版本 |
|---|---|---|
header() | 發送原始 HTTP 標頭(如重導向、Content-Type、快取控制) | 3 |
headers_list() | 返回已發送或待發送的回應標頭列表 | 5 |
headers_sent() | 檢查 HTTP 標頭是否已發送,並返回發送位置 | 3 |
setcookie() | 發送 HTTP Cookie(自動 URL 編碼值) | 3 |
setrawcookie() | 發送 HTTP Cookie(不進行 URL 編碼) | 5 |
<?php
header('Location: https://example.com/new-page.php');
exit;
?>
<?php
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['status' => 'ok', 'data' => [1,2,3]]);
?>
<?php
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
?>
<?php
// 過期時間 1 小時,僅 HTTPS、HttpOnly、SameSite=Lax
setcookie('user_id', '12345', [
'expires' => time() + 3600,
'path' => '/',
'domain' => '',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax'
]);
?>
<?php
if (!headers_sent($file, $line)) {
header('X-Custom: value');
} else {
error_log("Headers already sent in $file on line $line");
}
?>
header() 必須在任何實際輸出(HTML、空白、echo、print)之前呼叫,否則會觸發「Headers already sent」警告。headers_list() 除錯時可查看即將發送的標頭。httponly 與 secure 提升安全性。