我应该如何阅读任何头在PHP?

例如自定义报头:X-Requested-With。


当前回答

我是这么做的。如果$header_name没有被传递,你需要获取所有的头信息:

<?php
function getHeaders($header_name=null)
{
    $keys=array_keys($_SERVER);

    if(is_null($header_name)) {
            $headers=preg_grep("/^HTTP_(.*)/si", $keys);
    } else {
            $header_name_safe=str_replace("-", "_", strtoupper(preg_quote($header_name)));
            $headers=preg_grep("/^HTTP_${header_name_safe}$/si", $keys);
    }

    foreach($headers as $header) {
            if(is_null($header_name)){
                    $headervals[substr($header, 5)]=$_SERVER[$header];
            } else {
                    return $_SERVER[$header];
            }
    }

    return $headervals;
}
print_r(getHeaders());
echo "\n\n".getHeaders("Accept-Language");
?>

在我看来,它比其他答案中给出的大多数例子要简单得多。这也会获得方法(GET/POST/etc.)和在获取所有头部时请求的URI,如果你试图在日志记录中使用它,这可能很有用。

输出如下:

Array ( [HOST] => 127.0.0.1 [USER_AGENT] => Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:28.0) Gecko/20100101 Firefox/28.0 [ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 [ACCEPT_LANGUAGE] => en-US,en;q=0.5 [ACCEPT_ENCODING] => gzip, deflate [COOKIE] => PHPSESSID=MySessionCookieHere [CONNECTION] => keep-alive )

en-US,en;q=0.5

其他回答

PHP 7:空联合运算符

//$http = 'SCRIPT_NAME';
$http = 'X_REQUESTED_WITH';
$http = strtoupper($http);
$header = $_SERVER['HTTP_'.$http] ?? $_SERVER[$http] ?? NULL;

if(is_null($header)){
    die($http. ' Not Found');
}
echo $header;

从PHP 5.4.0开始,你可以使用getallheaders函数返回所有请求头作为关联数组:

var_dump(getallheaders());

// array(8) {
//   ["Accept"]=>
//   string(63) "text/html[...]"
//   ["Accept-Charset"]=>
//   string(31) "ISSO-8859-1[...]"
//   ["Accept-Encoding"]=>
//   string(17) "gzip,deflate,sdch"
//   ["Accept-Language"]=>
//   string(14) "en-US,en;q=0.8"
//   ["Cache-Control"]=>
//   string(9) "max-age=0"
//   ["Connection"]=>
//   string(10) "keep-alive"
//   ["Host"]=>
//   string(9) "localhost"
//   ["User-Agent"]=>
//   string(108) "Mozilla/5.0 (Windows NT 6.1; WOW64) [...]"
// }

在此之前,此函数仅在PHP作为Apache/NSAPI模块运行时有效。

为了让事情变得简单,以下是如何得到你想要的:

简单:

$headerValue = $_SERVER['HTTP_X_REQUESTED_WITH'];

或者当你需要一次得到一个:

<?php
/**
 * @param $pHeaderKey
 * @return mixed
 */
function get_header( $pHeaderKey )
{
    // Expanded for clarity.
    $headerKey = str_replace('-', '_', $pHeaderKey);
    $headerKey = strtoupper($headerKey);
    $headerValue = NULL;
    // Uncomment the if when you do not want to throw an undefined index error.
    // I leave it out because I like my app to tell me when it can't find something I expect.
    //if ( array_key_exists($headerKey, $_SERVER) ) {
    $headerValue = $_SERVER[ $headerKey ];
    //}
    return $headerValue;
}
// X-Requested-With mainly used to identify Ajax requests. Most JavaScript frameworks
// send this header with value of XMLHttpRequest, so this will not always be present.
$header_x_requested_with = get_header( 'X-Requested-With' );

其他的头文件也在超级全局数组$_SERVER中,你可以在这里阅读如何获取它们:http://php.net/manual/en/reserved.variables.server.php

你会发现$_SERVER全局变量中所有的HTTP头都以大写HTTP_开头,破折号(-)替换为下划线(_)。

例如,你的X-Requested-With可以在:

$_SERVER['HTTP_X_REQUESTED_WITH']

从$_SERVER变量创建一个关联数组可能很方便。这可以在几种风格中完成,但这里有一个输出驼峰键的函数:

$headers = array();
foreach ($_SERVER as $key => $value) {
    if (strpos($key, 'HTTP_') === 0) {
        $headers[str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
    }
}

现在只需使用$headers['XRequestedWith']来检索所需的标头。

PHP手册$_SERVER: http://php.net/manual/en/reserved.variables.server.php

如果:你只需要一个头文件,而不是所有的头文件,最快的方法是:

<?php
// Replace XXXXXX_XXXX with the name of the header you need in UPPERCASE (and with '-' replaced by '_')
$headerStringValue = $_SERVER['HTTP_XXXXXX_XXXX'];

ELSE IF:你将PHP作为Apache模块运行,或者在php5.4中使用FastCGI(简单方法):

apache_request_headers ()

<?php
$headers = apache_request_headers();

foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}

ELSE:在任何其他情况下,您可以使用(用户域实现):

<?php
function getRequestHeaders() {
    $headers = array();
    foreach($_SERVER as $key => $value) {
        if (substr($key, 0, 5) <> 'HTTP_') {
            continue;
        }
        $header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
        $headers[$header] = $value;
    }
    return $headers;
}

$headers = getRequestHeaders();

foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}

参见: getallheaders() (PHP >= 5.4)跨平台版本apache_request_headers()的别名 apache_response_headers() -获取所有HTTP响应头。 headers_list() -获取要发送的报头列表。