Use PHP to get all HTTP request headers

Source: Internet
Author: User

Lao Wang

In PHP, to get all the HTTP request headers, you can use the Getallheaders method, but this method does not exist in any environment, for example, you use fastcgi way to run PHP, there is no such method, so we need to consider other methods, fortunately There's something we want in $_server, and it's the HTTP request header that starts with the key name HTTP_:

$headers = array();
foreach ($_SERVER as $key => $value) {
    if (‘HTTP_‘ == substr($key, 0, 5)) {
        $headers[str_replace(‘_‘, ‘-‘, substr($key, 5))] = $value;
    }
}


The code is simple, and it is important to note that the name of the header is not case-sensitive in the RfC.

However, not all HTTP request headers are in the form of keys that start with HTTP_, such as Authorization,content-length,content-type. So in order to get all the HTTP request headers, you need to add the following code:

if (isset($_SERVER[‘PHP_AUTH_DIGEST‘])) {
    $header[‘AUTHORIZATION‘] = $_SERVER[‘PHP_AUTH_DIGEST‘]);
} elseif (isset($_SERVER[‘PHP_AUTH_USER‘]) && isset($_SERVER[‘PHP_AUTH_PW‘])) {
    $header[‘AUTHORIZATION‘] = base64_encode($_SERVER[‘PHP_AUTH_USER‘] . ‘:‘ . $_SERVER[‘PHP_AUTH_PW‘]));
}
if (isset($_SERVER[‘CONTENT_LENGTH‘])) {
    $header[‘CONTENT-LENGTH‘] = $_SERVER[‘CONTENT_LENGTH‘];
}
if (isset($_SERVER[‘CONTENT_TYPE‘])) {
    $header[‘CONTENT-TYPE‘] = $_SERVER[‘CONTENT_TYPE‘];
}


Here by the way how to get the HTTP response header, give a simple example to illustrate the problem:

file_get_contents (' http://www.baidu.com ');
Var_dump ($http _response_header);

There is an easier way to do this:

Var_dump (get_headers (' http://www.baidu.com '));

Getting a response header is much simpler than getting a request header.

Supplemental Documentation: HTTP://WWW.ROOFTOPSOLUTIONS.NL/ARTICLE/223

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.