WordPress – How to use get_headers() behind proxy server

When a WordPress installation sits behind a proxy server the proxy settings are added to wp-config.php to tell WordPress how to access the internet.

Without this WordPress will be unable to check for updates and run PHP functions that rely on the internet, such as get_headers()

For example, in wp-config.php you would have

  define('WP_PROXY_HOST', 'proxy.dev.local');
  define('WP_PROXY_PORT', '8080');
  define('WP_PROXY_BYPASS_HOSTS', 'localhost');

If you were to use the PHP function get_headers() in this situation you will find the function always returns FALSE – this is because it will fail to access the internet.

To use get_headers() behind a proxy server you will need to also use the stream_context_set_default() function. stream_context_set_default() is used before get_headers() is called and prepares the code for accessing the internet.

For example, if you needed to run this

$check_value = get_headers($url);

You will need to use stream_context_set_default() before get_headers().

Note the example below uses the defined constants set in wp-config.php. It assumes the proxy does not require any authentication, if it does read more about how to configure authentication on the php manual page – stream_context_set_default().

 stream_context_set_default(
                array(
                    'http' => array(
                    'proxy' => "tcp://".WP_PROXY_HOST.":".WP_PROXY_PORT,
                    'request_fulluri' => true
                  )
                 )
                ); 
$check_value = get_headers($url);