Home >Backend Development >PHP Tutorial >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:
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!