accept标头 php,如何在PHP中读取任何请求标头

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

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

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

Sabya asked 2019-02-28T12:09:45Z

14个解决方案

349 votes

$_SERVER['HTTP_X_REQUESTED_WITH']

RFC3875,4.1.18:

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

Quassnoi answered 2019-02-28T12:11:14Z

256 votes

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

// 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()

$headers = apache_request_headers();

foreach ($headers as $header => $value) {

echo "$header: $value
\n";

}

ELSE:在任何其他情况下,您都可以使用(userland implementation):

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
\n";

}

也可以看看:

getallheaders() - (PHP&gt; = 5.4)跨平台版别名apache_request_headers()apache_response_headers() - 获取所有HTTP响应头。

headers_list() - 获取要发送的标头列表。

Jacco answered 2019-02-28T12:10:39Z

47 votes

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

例如,您的$_SERVER可以在以下位置找到:

$_SERVER['HTTP_X_REQUESTED_WITH']

从$_SERVER变量创建关联数组可能很方便。 这可以用几种样式完成,但这是一个输出camelcased键的函数:

$headers = array();

foreach ($_SERVER as $key => $value) {

if (strpos($key, 'HTTP_') === 0) {

$headers[str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;

}

}

现在只需使用$_SERVER来检索所需的标题。

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

Thomas Jensen answered 2019-02-28T12:12:21Z

18 votes

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

Salman A answered 2019-02-28T12:13:07Z

6 votes

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

Glenn Plas answered 2019-02-28T12:14:14Z

5 votes

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

Milap Kundalia answered 2019-02-28T12:15:23Z

3 votes

为了简单起见,您可以通过以下方式获得所需的内容:

简单:

$headerValue = $_SERVER['HTTP_X_REQUESTED_WITH'];

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

/**

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

b01 answered 2019-02-28T12:16:12Z

2 votes

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

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

Rajesh answered 2019-02-28T12:16:40Z

1 votes

这就是我在做的方式。 如果未传递$ header_name,则需要获取所有标头:

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 / etc。)和获取所有标头时请求的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

Jonnycake answered 2019-02-28T12:17:26Z

0 votes

这是一个简单的方法。

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

}

}

kehers answered 2019-02-28T12:17:57Z

0 votes

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

foreach($_SERVER as $key => $value){

echo '$_SERVER["'.$key.'"] = '.$value."
";

}

?>

Technolust answered 2019-02-28T12:18:25Z

0 votes

function getCustomHeaders()

{

$headers = array();

foreach($_SERVER as $key => $value)

{

if(preg_match("/^HTTP_X_/", $key))

$headers[$key] = $value;

}

return $headers;

}

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

ZiTAL answered 2019-02-28T12:18:54Z

0 votes

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

apache_request_headers()['Host']

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

Zigma Empire answered 2019-02-28T12:19:31Z

-1 votes

如果您有Apache服务器,这项工作

PHP代码:

$headers = apache_request_headers();

foreach ($headers as $header => $value) {

echo "$header: $value
\n";

}

结果:

Accept: */*

Accept-Language: en-us

Accept-Encoding: gzip, deflate

User-Agent: Mozilla/4.0

Host: www.example.com

Connection: Keep-Alive

Emanuel Nogueiras answered 2019-02-28T12:20:13Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值