如何读取 PHP 中的任何请求标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/541430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:02:19  来源:igfitidea点击:

How do I read any request header in PHP

phphttp-headers

提问by Sabya

How should I read any header in PHP?

我应该如何阅读 PHP 中的任何标题?

For example the custom header: X-Requested-With.

例如自定义标头:X-Requested-With.

回答by Quassnoi

$_SERVER['HTTP_X_REQUESTED_WITH']

RFC3875, 4.1.18:

RFC3875,4.1.18

Meta-variables with names beginning with HTTP_contain values read from the client request header fields, if the protocol used is HTTP. The HTTP header field name is converted to upper case, has all occurrences of -replaced with _and has HTTP_prepended to give the meta-variable name.

HTTP_如果使用的协议是 HTTP,则名称以 开头的元变量包含从客户端请求标头字段读取的值。HTTP 标头字段名称被转换为大写,所有出现的 都-被替换为_并已HTTP_预先给出元变量名称。

回答by Jacco

IF: you only need a single header, instead of allheaders, the quickest method is:

IF:您只需要一个标题,而不是所有标题,最快的方法是:

<?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: you run PHP as an Apache module or, as of PHP 5.4, using FastCGI (simple method):


否则:您将 PHP 作为 Apache 模块运行,或者,从 PHP 5.4 开始,使用 FastCGI(简单方法):

apache_request_headers()

apache_request_headers()

<?php
$headers = apache_request_headers();

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


ELSE:In any other case, you can use (userland implementation):


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";
}


See Also:
getallheaders()- (PHP >= 5.4) cross platform editionAlias of apache_request_headers()apache_response_headers()- Fetch all HTTP response headers.
headers_list()- Fetch a list of headers to be sent.


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

回答by Thomas Jensen

You should find all HTTP headers in the $_SERVERglobal variable prefixed with HTTP_uppercased and with dashes (-) replaced by underscores (_).

您应该在$_SERVER全局变量中找到所有以HTTP_大写字母为前缀的HTTP 标头,并将短划线 (-) 替换为下划线 (_)。

For instance your X-Requested-Withcan be found in:

例如,您X-Requested-With可以在以下位置找到:

$_SERVER['HTTP_X_REQUESTED_WITH']

It might be convenient to create an associative array from the $_SERVERvariable. This can be done in several styles, but here's a function that outputs camelcased keys:

$_SERVER变量创建关联数组可能会很方便。这可以通过多种方式完成,但这里有一个输出驼峰键的函数:

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

Now just use $headers['XRequestedWith']to retrieve the desired header.

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

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

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

回答by Salman A

Since PHP 5.4.0 you can use getallheadersfunction which returns all request headers as an associative array:

自 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) [...]"
// }

Earlier this function worked only when PHP was running as an Apache/NSAPI module.

早些时候,此功能仅在 PHP 作为 Apache/NSAPI 模块运行时才起作用。

回答by Glenn Plas

strtoloweris lacking in several of the proposed solutions, RFC2616 (HTTP/1.1) defines header fields as case-insensitive entities. The whole thing, not just the valuepart.

strtolower一些提议的解决方案缺乏,RFC2616 (HTTP/1.1) 将标头字段定义为不区分大小写的实体。整个事情,而不仅仅是价值部分。

So suggestions like only parsing HTTP_entries are wrong.

所以像只解析HTTP_条目这样的建议是错误的。

Better would be like this:

最好是这样:

if (!function_exists('getallheaders')) {
    foreach ($_SERVER as $name => $value) {
        /* RFC2616 (HTTP/1.1) defines header fields as case-insensitive entities. */
        if (strtolower(substr($name, 0, 5)) == 'http_') {
            $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
        }
    }
    $this->request_headers = $headers;
} else {
    $this->request_headers = getallheaders();
}

Notice the subtle differences with previous suggestions. The function here also works on php-fpm (+nginx).

请注意与先前建议的细微差别。这里的函数也适用于 php-fpm (+nginx)。

回答by Milap Kundalia

Pass a header name to this function to get its value without using forloop. Returns null if header not found.

将标头名称传递给此函数以获取其值,而无需使用for循环。如果未找到标头,则返回 null。

/**
 * @var string $headerName case insensitive header name
 *
 * @return string|null header value or null if not found
 */
function get_header($headerName)
{
    $headers = getallheaders();
    return isset($headerName) ? $headers[$headerName] : null;
}

Note: this works only with Apache server, see: http://php.net/manual/en/function.getallheaders.php

注意:这仅适用于 Apache 服务器,请参阅:http: //php.net/manual/en/function.getallheaders.php

Note: this function will process and load all of the headers to the memory and it's less performant than a forloop.

注意:此函数将处理所有标头并将其加载到内存中,它的性能不如for循环。

回答by b01

To make things simple, here is how you can get just the one you want:

为简单起见,您可以通过以下方式获得您想要的:

Simple:

简单的:

$headerValue = $_SERVER['HTTP_X_REQUESTED_WITH'];

or when you need to get one at a time:

或者当您需要一次获得一个时:

<?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' );

The other headers are also in the super global array $_SERVER, you can read about how to get at them here: http://php.net/manual/en/reserved.variables.server.php

其他标头也在超级全局数组 $_SERVER 中,您可以在此处阅读有关如何获取它们的信息:http: //php.net/manual/en/reserved.variables.server.php

回答by Rajesh

I was using CodeIgniter and used the code below to get it. May be useful for someone in future.

我正在使用 CodeIgniter 并使用下面的代码来获取它。将来可能对某人有用。

$this->input->get_request_header('X-Requested-With');

回答by Jonnycake

Here's how I'm doing it. You need to get all headers if $header_name isn't passed:

这就是我的做法。如果 $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");
?>

It looks a lot simpler to me than most of the examples given in other answers. This also gets the method (GET/POST/etc.) and the URI requested when getting all of the headers which can be useful if you're trying to use it in logging.

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

Here's the output:

这是输出:

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

回答by Technolust

This small PHP snippet can be helpful to you:

这个小的 PHP 代码片段可能对您有所帮助:

<?php
foreach($_SERVER as $key => $value){
echo '$_SERVER["'.$key.'"] = '.$value."<br />";
}
?>