How to Handle Header Retrieval in PHP
Requirement: Reading any request header in PHP.
Single Header Solution:
When working with a single specific header rather than all headers, the most efficient method is:
// Replace XXXXXX_XXXX with the header you need, in uppercase and '-' replaced by '_' $headerValue = $_SERVER['HTTP_XXXXXX_XXXX'];
Retrieving All Headers (Apache Module or FastCGI):
Two methods are available for retrieving all headers when using Apache or FastCGI:
1. apache_request_headers():
Returns an array with all header values.
2. Built-in Method:
foreach ($_SERVER as $key => $value) { if (substr($key, 0, 5) !== 'HTTP_') { continue; } // Process headers... }
Retrieving All Headers (Other Platforms):
For other platforms, a userland implementation can be used:
function getRequestHeaders() { // ... (Implementation same as above) }
Advanced Note:
For PHP versions 5.4 and up, the getallheaders() function may also be used as a cross-platform equivalent of apache_request_headers().
The above is the detailed content of How to Efficiently Retrieve Request Headers in PHP?. For more information, please follow other related articles on the PHP Chinese website!