如何在 PHP 中读取任何请求标头 [英] How do I read any request header in PHP

查看:23
本文介绍了如何在 PHP 中读取任何请求标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How should I read any header in PHP?

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

推荐答案

IF:你只需要一个header,而不是all headers,最快的方法是:

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:您将 PHP 作为 Apache 模块运行,或者从 PHP 5.4 开始,使用 FastCGI(简单方法):


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


ELSE: 在任何其他情况下,您都可以使用(用户态实现):


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


另请参阅:
getallheaders() - (PHP >= 5.4) 跨平台版本 apache_request_headers()的别名apache_response_headers() - 获取所有 HTTP 响应标头.
headers_list() - 获取要发送的标头列表.


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.

这篇关于如何在 PHP 中读取任何请求标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆