If you use Nginx, PHP-FPM or any other FastCGI method of running PHP you’ve probably noticed that the function getallheaders() does not exist. There are many creative workarounds in the wild, but PHP offers two very nice features to ease your pain.
First, PHP has an internal function called function_exists() which lets you see if a function is already declared. With namespaces and objects this isn’t a very big deal so many people don’t know about this little function, but when a built-in function comes and goes, it can be a lifesaver.
Second, PHP lets you declare a function that has global scope if you are inside a function that has global scope.
If we put them together, we have a few lines we can include before we process any headers that will declare getallheaders() if it does not exist. If it does exist, nothing changes.
if (!function_exists('getallheaders')) {
function getallheaders() {
$headers = [];
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
}
This idea was shamelessly lifted from the user contributed comments at http://php.net/manual/en/function.getallheaders.php. Thanks joyview at gmail dot com
Did you find this post useful or have questions or comments? Please let me know!
Why replacing underline to space then space to dash? wouldn’t this just work: $headers[ucwords(strtolower(substr($name, 5)))] = $value; ?
Ok say you have to, then why not just directly replace _ to – without first replacing it to space?
@Temirbek Nuradil uulu
It guarantees normalization. The idea is to get to uppercase string separated by hyphens. Spaces and underscores are converted to hyphens in the process.
Pingback: PHP - Get Custom Headers when Using Nginx with php-fpm - Tutorial Guruji