Brain Goo

Carpe Crap ’em

Brain Goo header image 2

 

 

HOWTO use PHP getallheaders() under FastCGI (PHP-FPM, nginx, etc.)

July 14th, 2015 · No Comments

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!

Tags: How Tos · php · Programming

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment