WordPress wp-cli generates error: “Call to undefined function getallheaders”

The wp-cli tool is a very handy way to execute WordPress tasks from the command line. However if the WordPress Site contains plugins or theme initialization code that calls the PHP getallheaders method then wp-cli will not work. It will instead return the following error in response to every command:

Fatal error: Call to undefined function getallheaders()

Read More

This is happening on PHP v 5.4.4. What is the best workaround for this problem?

Related posts

2 comments

  1. Some PHP functions are dependent on the underlying Server Application Programming Interface. The Apache SAPI of course supports the getallheaders method. But some Command Line Interfaces do not. In this case wp-cli uses the PHP-FPM (FastCGI Process Manager) as the SAPI. However according to this PHP Bug Report 62596, PHP-FPM in PHP v5.4 does not support getallheaders. Therefore when wp-cli attempts to bootstrap the WordPress Site in CLI mode, the undefined function errors occurs.

    The recommended solution is to add these lines to the wp-config.php file. The wp-cli tool defines a constant called: WP_CLI. If this constant is set then simply define a dummy version of the getallheaders. This should not cause a problem because the WP App is not getting any HTTP Headers anyway when running in CLI mode. Here is some sample code that can be inserted into wp-config.php

    if ( defined( 'WP_CLI' ) ) {
        if ( !function_exists ( 'getallheaders' ) ) {
            function getallheaders() {return array();}
        }
    }
    
  2. In case you are doing some syncing from a website/application via API to WordPress and you actually need the getallheaders function to work, you can use this solution :

    $headers = [];
    if ( function_exists( 'getallheaders' ) ) {
        $headers = getallheaders();
    } else {
        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;
        }
        $headers = getallheaders();
    }
    

Comments are closed.