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

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


当前回答

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:空联合运算符

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

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

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

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

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

你会发现$_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

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

简单:

$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