Home >Backend Development >PHP Tutorial >How Can I Access Request Headers in PHP?

How Can I Access Request Headers in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-12-09 09:02:07707browse

How Can I Access Request Headers in PHP?

Accessing Request Headers in PHP

Retrieving specific or all request headers is a common task in PHP development. Here are the different approaches you can use:

Single Header Retrieval (Apache Module or FastCGI)

If you only need a particular header, the most efficient way is to access it directly using the HTTP header name as the key in the $_SERVER array. Replace XXXXXX_XXXX with the header name in uppercase (with hyphens replaced by underscores).

// Retrieve the "X-Requested-With" header value
$headerValue = $_SERVER['HTTP_X_REQUESTED_WITH'];

All Headers Retrieval

Apache Module or FastCGI (Simple Method)

The apache_request_headers() function provides access to all request headers.

$headers = apache_request_headers();

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

All Other Cases (Userland Implementation)

In cases where apache_request_headers() is unavailable, you can use a custom function to extract headers from the $_SERVER array.

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

  • getallheaders() (PHP >= 5.4): An alternative to apache_request_headers() that works cross-platform.
  • apache_response_headers(): Retrieves HTTP response headers.
  • headers_list(): Lists headers to be sent in the response.

The above is the detailed content of How Can I Access Request Headers 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