Home > Backend Development > PHP Tutorial > How Can I Access Any HTTP Request Header in PHP?

How Can I Access Any HTTP Request Header in PHP?

Susan Sarandon
Release: 2024-12-14 14:43:10
Original
165 people have browsed it

How Can I Access Any HTTP Request Header in PHP?

How to Read Any Request Header in PHP

Problem:

How can you access any HTTP header, including custom headers, in PHP?

Answer:

There are several methods to read request headers in PHP, depending on your specific requirements:

Single Header Retrieval:

If you only need to retrieve a single header value, use the following syntax:

<?php
// Replace XXXXXX_XXXX with the name of the header you need in UPPERCASE (and with '-' replaced by '_')
$headerStringValue = $_SERVER['HTTP_XXXXXX_XXXX'];
?>
Copy after login

Apache Module or FastCGI (PHP 5.4 ):

If PHP is running as an Apache module or using FastCGI with PHP 5.4 or later, you can use the apache_request_headers() function:

<?php
$headers = apache_request_headers();

foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}
?>
Copy after login

Fallback Method:

In all other cases, you can use the following 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 />\n";
}
?>
Copy after login

Additional Functions:

  • getallheaders() (PHP 5.4 ): Alias of apache_request_headers().
  • apache_response_headers(): Fetches all HTTP response headers.
  • headers_list(): Fetches a list of headers to be sent.

The above is the detailed content of How Can I Access Any HTTP Request Header in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template