2024 年日本 PHP 研討會

$http_response_header

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

$http_response_headerHTTP 回應標頭

說明

$http_response_header 陣列get_headers() 函式類似。當使用 HTTP 包裝器 時,$http_response_header 會填入 HTTP 回應標頭。 $http_response_header 將會在 局部作用域 中建立。

範例

範例 #1 $http_response_header 範例

<?php
function get_contents() {
file_get_contents("http://example.com");
var_dump($http_response_header); // 變數會在局部作用域中填入
}
get_contents();
var_dump($http_response_header); // 呼叫 get_contents() 並不會在函式作用域外填入變數
?>

上述範例的輸出會類似於

array(9) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
  [2]=>
  string(29) "Server: Apache/2.2.3 (CentOS)"
  [3]=>
  string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
  [4]=>
  string(27) "ETag: "280100-1b6-80bfd280""
  [5]=>
  string(20) "Accept-Ranges: bytes"
  [6]=>
  string(19) "Content-Length: 438"
  [7]=>
  string(17) "Connection: close"
  [8]=>
  string(38) "Content-Type: text/html; charset=UTF-8"
}

Warning: Undefined variable $http_response_header
NULL

另請參閱

新增註解

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

nicolas at toniazzi dot net
11 年前
請注意,HTTP 包裝器對於標頭行有 1024 個字元的硬性限制。
任何超過此長度的 HTTP 標頭都會被忽略,並且不會出現在 $http_response_header 中。

cURL 擴充套件沒有這個限制。

http_fopen_wrapper.c: #define HTTP_HEADER_BLOCK_SIZE 1024
MangaII
9 年前
用於取得格式化標頭(包含回應碼)的解析函式

<?php

function parseHeaders( $headers )
{
$head = array();
foreach(
$headers as $k=>$v )
{
$t = explode( ':', $v, 2 );
if( isset(
$t[1] ) )
$head[ trim($t[0]) ] = trim( $t[1] );
else
{
$head[] = $v;
if(
preg_match( "#HTTP/[0-9\.]+\s+([0-9]+)#",$v, $out ) )
$head['reponse_code'] = intval($out[1]);
}
}
return
$head;
}

print_r(parseHeaders($http_response_header));

/*
陣列
(
[0] => HTTP/1.1 200 OK
[reponse_code] => 200
[Date] => 週五, 01 五月 2015 12:56:09 GMT
[Server] => Apache
[X-Powered-By] => PHP/5.3.3-7+squeeze18
[Set-Cookie] => PHPSESSID=ng25jekmlipl1smfscq7copdl3; path=/
[Expires] => 週四, 19 十一月 1981 08:52:00 GMT
[Cache-Control] => no-store, no-cache, must-revalidate, post-check=0, pre-check=0
[Pragma] => no-cache
[Vary] => Accept-Encoding
[Content-Length] => 872
[Connection] => close
[Content-Type] => text/html
)
*/

?>
To Top