Home >Backend Development >PHP Tutorial >How Can I Access Any HTTP 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:
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!