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
Susan SarandonOriginal
2024-12-14 14:43:10166browse

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

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

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

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!

Statement:
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