调用未定义函数apache_request_headers()的原因及求助
Hey there, let's break down why you're hitting that frustrating fatal error when trying to use apache_request_headers(), and how to fix it quickly.
Why the Error Happens
The apache_request_headers() function is only available when PHP is running as an Apache module. If your server uses Nginx with PHP-FPM, CGI, or any non-Apache server setup, this function doesn't exist in your environment—hence the "undefined function" error.
Quick Solutions to Grab Request Headers
Here are a few reliable ways to get those headers without relying on Apache-specific functions:
Use the cross-environment
getallheaders()function
This is the easiest fix for PHP 5.4 and newer (which most modern servers use). It works exactly likeapache_request_headers()but works across all server environments. Just replace your existing code with:$headers = getallheaders(); print_r($headers);Add a compatibility function for older PHP versions
If you're stuck on PHP < 5.4 (though this is rare these days), you can manually define a replacement function that mimicsapache_request_headers()by parsing the$_SERVERsuperglobal. Drop this code at the top of your script before calling the function:if (!function_exists('apache_request_headers')) { function apache_request_headers() { $headers = []; foreach ($_SERVER as $name => $value) { if (substr($name, 0, 5) === 'HTTP_') { // Convert header names like HTTP_USER_AGENT to "User-Agent" $headerName = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5))))); $headers[$headerName] = $value; } } return $headers; } }Once this is in place, your original call to
apache_request_headers()will work as expected.Verify your server environment
You can confirm your server setup by checking the "Server API" section in your phpinfo output. If it says "FPM/FastCGI" or "CGI", you're on a non-Apache setup—stick with the cross-environment solutions above. If it says "Apache 2.0 Handler" and you still get the error, double-check that your PHP installation wasn't compiled without Apache support (though this is uncommon).
Give these solutions a test, and you should be able to access those request headers without any more errors!
内容的提问来源于stack exchange,提问作者Matheus Marzochi

