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

发布于 2024-07-14 02:12:05 字数 75 浏览 4 评论 0原文

我应该如何读取 PHP 中的任何标头?

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

How should I read any header in PHP?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

牵你手 2024-07-21 02:12:05

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:将 PHP 作为 Apache 模块运行,或者从 PHP 5.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 响应标头。< br>
headers_list() - 获取要发送的标头列表。

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

<?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):

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):

<?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 edition Alias of apache_request_headers()
apache_response_headers() - Fetch all HTTP response headers.
headers_list() - Fetch a list of headers to be sent.

轮廓§ 2024-07-21 02:12:05
$_SERVER['HTTP_X_REQUESTED_WITH']

RFC3875,4.1.18:

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

$_SERVER['HTTP_X_REQUESTED_WITH']

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.

踏月而来 2024-07-21 02:12:05

您应该在 $_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'] 来检索所需的标头。

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

You should find all HTTP headers in the $_SERVER global variable prefixed with HTTP_ uppercased and with dashes (-) replaced by underscores (_).

For instance your X-Requested-With can be found in:

$_SERVER['HTTP_X_REQUESTED_WITH']

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

$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.

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

a√萤火虫的光℡ 2024-07-21 02:12:05

从 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 模块运行时才起作用。

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

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.

梦里南柯 2024-07-21 02:12:05

将标头名称传递给此函数以获取其值,而无需使用 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;
}

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

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

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

/**
 * @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

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

旧伤慢歌 2024-07-21 02:12:05

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

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

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

$this->input->get_request_header('X-Requested-With');
南巷近海 2024-07-21 02:12:05

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

因此,诸如仅解析 HTTP_ 条目之类的建议是错误的。

更好的是这样的:

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();
}

注意与之前建议的细微差别。 这里的功能也适用于 php-fpm (+nginx)。

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

So suggestions like only parsing HTTP_ entries are wrong.

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).

魄砕の薆 2024-07-21 02:12:05

如果只需要检索一个密钥,例如需要 "Host" 地址,那么我们可以使用

apache_request_headers()['Host']

这样我们就可以避免循环并将其内联到回显输出

if only one key is required to retrieved, For example "Host" address is required, then we can use

apache_request_headers()['Host']

So that we can avoid loops and put it inline to the echo outputs

野の 2024-07-21 02:12:05

为了简单起见,以下是如何获取您想要的:

简单:

$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

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

橘和柠 2024-07-21 02:12:05

如果您有 Apache 服务器

PHP 代码:

$headers = apache_request_headers();

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

结果:

Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0
Host: www.example.com
Connection: Keep-Alive

This work if you have an Apache server

PHP Code:

$headers = apache_request_headers();

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

Result:

Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0
Host: www.example.com
Connection: Keep-Alive
烟花易冷人易散 2024-07-21 02:12:05

我是这样做的。 如果未传递 $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/等)以及获取所有标头时请求的 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

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

<?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.

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
李不 2024-07-21 02:12:05

这是一个简单的方法。

// echo get_header('X-Requested-With');
function get_header($field) {
    $headers = headers_list();
    foreach ($headers as $header) {
        list($key, $value) = preg_split('/:\s*/', $header);
        if ($key == $field)
            return $value;
    }
}

Here is an easy way to do it.

// echo get_header('X-Requested-With');
function get_header($field) {
    $headers = headers_list();
    foreach ($headers as $header) {
        list($key, $value) = preg_split('/:\s*/', $header);
        if ($key == $field)
            return $value;
    }
}
陪你到最终 2024-07-21 02:12:05

这个 PHP 小片段会对您有所帮助:

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

This small PHP snippet can be helpful to you:

<?php
foreach($_SERVER as $key => $value){
echo '$_SERVER["'.$key.'"] = '.$value."<br />";
}
?>
寒冷纷飞旳雪 2024-07-21 02:12:05
function getCustomHeaders()
{
    $headers = array();
    foreach($_SERVER as $key => $value)
    {
        if(preg_match("/^HTTP_X_/", $key))
            $headers[$key] = $value;
    }
    return $headers;
}

我使用此函数来获取自定义标头,如果标头从“HTTP_X_”开始,我们将推入数组:)

function getCustomHeaders()
{
    $headers = array();
    foreach($_SERVER as $key => $value)
    {
        if(preg_match("/^HTTP_X_/", $key))
            $headers[$key] = $value;
    }
    return $headers;
}

I use this function to get the custom headers, if the header starts from "HTTP_X_" we push in the array :)

伊面 2024-07-21 02:12:05

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 7: Null Coalesce Operator

//$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;
御守 2024-07-21 02:12:05

下面的代码适用于我获取标头中提交的任何特定数据

foreach (getallheaders() as $name => $value) {
   if($name=='Authorization') //here you can search by name
   $Authorization= $value ;
}

Below code works for me to get any specific data submitted in the header

foreach (getallheaders() as $name => $value) {
   if($name=='Authorization') //here you can search by name
   $Authorization= $value ;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文