Three workarounds for “Error establishing a database connection” when including wp-load.php form a WordPress Network

Let’s say you have a good reason for include a wp-load.php from a WordPress Network (multisite) install in an external script (some reasons aren’t good enough).

If this is your case and you have the WordPress Network installation inside a subfolder and you try to run your script you may get an “Error establishing a database connection”.

These are three complementary ways to workaround this issue:

Use wp-cli

If you are on a VPS, maybe calling your script in a cronjob, you can use the WordPress command line interface like that:

wp --path=/path/to/your/wordpress/installation eval-file path/to/your/script.php

Of course you will need to replace /path/to/your/wordpress/installation with the actual path of the root directory where you have your WordPress files and path/to/your/script.php with the path of your script.

Use sunrise.php

sunrise.php is a PHP file you can place inside the wp-content of your WordPress Network and it gets run right when the WordPress multisite bootstrap process starts. There you can place an snippet such as that one:

if (strpos($_SERVER['REQUEST_URI'],'/subdirectory') === false)
    $_SERVER['REQUEST_URI'] = '/subdirectory/';

And things will work again as expected. Make sure you replace subdirectory with the name of the root folder where you have your WordPress Network files.

Set $_SERVER[‘REQUEST_URI’] before requiring wp-load.php

In your script, you can workaround this issue by setting $_SERVER['REQUEST_URI'] to the name of your WordPress Network folder before you require wp-load.php in your script. Like that:

$_SERVER['REQUEST_URI'] = '/subdirectory/';
require_once( 'path/to/wp-load.php' );

More information

See WordPress Core Issue #27999: Problem with embedding WordPress Multisite in other PHP applications caused by path difference in ms-settings.