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

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


当前回答

我使用CodeIgniter,并使用下面的代码来获得它。也许将来对某人有用。

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

其他回答

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

我使用这个函数来获得自定义头,如果头从“HTTP_X_”开始,我们在数组中推送:)

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

简单:

$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

将头名称传递给该函数以获取其值,而不使用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.net/manual/en/function.getallheaders.php

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

如果您有一台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

这里有一个简单的方法。

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