PHP Conference Japan 2024

getallheaders

(PHP 4, PHP 5, PHP 7, PHP 8)

getallheaders取得所有 HTTP 請求標頭

描述

getallheaders(): array

從目前的請求中取得所有 HTTP 標頭。

此函式是 apache_request_headers() 的別名。請閱讀 apache_request_headers() 文件以取得更多關於此函式如何運作的資訊。

參數

此函式沒有參數。

回傳值

一個包含目前請求中所有 HTTP 標頭的關聯陣列。

變更日誌

版本 描述
7.3.0 此函式在 FPM SAPI 中可用。

範例

範例 1 getallheaders() 範例

<?php

foreach (getallheaders() as $name => $value) {
echo
"$name: $value\n";
}

?>

參見

新增註解

使用者貢獻的註解 7 則註解

134
joyview at gmail dot com
16 年前
如果您使用 nginx 而不是 apache,這可能會很有用

<?php
if (!function_exists('getallheaders'))
{
function
getallheaders()
{
$headers = [];
foreach (
$_SERVER as $name => $value)
{
if (
substr($name, 0, 5) == 'HTTP_')
{
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return
$headers;
}
}
?>
17
michaelmcandrew at thirdsectordesign dot org
4 年前
處理不區分大小寫的標頭(根據 RFC2616)的簡單方法是透過內建的 array_change_key_case() 函式

$headers = array_change_key_case(getallheaders(), CASE_LOWER);
36
Anonymous
8 年前
有一個可以下載或透過 composer 安裝的 polyfill

https://github.com/ralouphie/getallheaders
28
lorro at lorro dot hu
19 年前
請注意,RFC2616 (HTTP/1.1) 將標頭欄位定義為不區分大小寫的實體。因此,getallheaders() 的陣列鍵應先轉換為小寫或大寫,然後再進行處理。
5
acidfilez at gmail dot com
13 年前
如果您正在上傳檔案,請不要忘記新增 content_type 和 content_lenght

<?php
function emu_getallheaders() {
foreach (
$_SERVER as $name => $value)
{
if (
substr($name, 0, 5) == 'HTTP_')
{
$name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
$headers[$name] = $value;
} else if (
$name == "CONTENT_TYPE") {
$headers["Content-Type"] = $value;
} else if (
$name == "CONTENT_LENGTH") {
$headers["Content-Length"] = $value;
}
}
return
$headers;
}
?>

chears magno c. heck
-2
majksner at gmail dot com
14 年前
用於 nginx 的 apache_request_headers 替代方案

<?php
if (!function_exists('apache_request_headers')) {
function
apache_request_headers() {
foreach(
$_SERVER as $key=>$value) {
if (
substr($key,0,5)=="HTTP_") {
$key=str_replace(" ","-",ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
$out[$key]=$value;
}else{
$out[$key]=$value;
}
}
return
$out;
}
}
?>
-1
divinity76 at gmail dot com
1 年前
警告,至少在 php-fpm 8.2.1 和 nginx 上,getallheaders() 將會回傳 "Content-Length" 和 "Content-Type",兩者都包含空字串,即使對於沒有這 2 個標頭的請求也是如此。您可以執行類似下列的操作

<?php
$request_headers
= getallheaders();
if((
$request_headers["Content-Type"] ?? null) === "" && ($request_headers["Content-Length"] ?? null) === "") {
// 可能是一個 getallheaders() 的錯誤,而不是實際的請求標頭。
unset($request_headers["Content-Type"], $request_headers["Content-Length"]);
}
?>

- 可能是 nginx 而非 php-fpm 的錯誤,我不確定。無論如何,真實的請求不會將它們留空字串。
To Top