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

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


当前回答

将头名称传递给该函数以获取其值,而不使用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循环。

其他回答

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

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

从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模块运行时有效。

将头名称传递给该函数以获取其值,而不使用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循环。

下面的代码为我工作,以获得任何特定的数据提交在头部

foreach (getallheaders() as $name => $value) {
   if($name=='Authorization') //here you can search by name
   $Authorization= $value ;
}
function getCustomHeaders()
{
    $headers = array();
    foreach($_SERVER as $key => $value)
    {
        if(preg_match("/^HTTP_X_/", $key))
            $headers[$key] = $value;
    }
    return $headers;
}

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