How do I read any request header in PHP

2019-01-01 03:04发布

How should I read any header in PHP?

For example the custom header: X-Requested-With.

14条回答
爱死公子算了
2楼-- · 2019-01-01 03:44

I was using CodeIgniter and used the code below to get it. May be useful for someone in future.

$this->input->get_request_header('X-Requested-With');
查看更多
低头抚发
3楼-- · 2019-01-01 03:44

This small PHP snippet can be helpful to you:

<?php
foreach($_SERVER as $key => $value){
echo '$_SERVER["'.$key.'"] = '.$value."<br />";
}
?>
查看更多
与君花间醉酒
4楼-- · 2019-01-01 03:46

Since PHP 5.4.0 you can use getallheaders function which returns all requested headers as an associative array:

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) [...]"
// }

Earlier this function worked only when PHP was running as an Apache/NSAPI module.

查看更多
余生请多指教
5楼-- · 2019-01-01 03:50

Here's how I'm doing it. You need to get all headers if $header_name isn't passed:

<?php
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");
?>

It looks a lot simpler to me than most of the examples given in other answers. This also gets the method (GET/POST/etc.) and the URI requested when getting all of the headers which can be useful if you're trying to use it in logging.

Here's the output:

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
查看更多
萌妹纸的霸气范
6楼-- · 2019-01-01 03:52

Here is an easy way to do it.

// 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;
    }
}
查看更多
高级女魔头
7楼-- · 2019-01-01 03:56

To make things simple, here is how you can get just the one you want:

Simple:

$headerValue = $_SERVER['HTTP_X_REQUESTED_WITH'];

or when you need to get one at a time:

<?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' );

The other headers are also in the super global array $_SERVER, you can read about how to get at them here: http://php.net/manual/en/reserved.variables.server.php

查看更多
登录 后发表回答