Solution:
Webserver and CLI run with different configs
Environment variables (like __DIR__
, connection settings (interpretations of “localhost” and application ports, and virtual-host directives and directory-root, can all vary between the two.
- Paths and Directory-root
- Connection settings
- Environment Variables
Paths and directory-root
Your paths may be are different between command-line and your webserver (apache/nginx?). Check them carefully to see what you’re actually trying to load
One of these is not like the others:
- relative path
/../../wp-load.php
- the constant
__DIR__
Echo realpath to see what is happening.
Run it again, both in a browser and via command-line.
// sync.php
<?php
echo __DIR__ . "\n";
echo realpath(__DIR__ . '/../'). "\n";
echo realpath(__DIR__ . '/../../'). "\n";
echo realpath(__DIR__ . '/../../wp-load.php'). "\n";
//require __DIR__ . '/../../wp-load.php';
//echo 'WordPress loaded!' . PHP_EOL;
Note: realpath
will return false if the file does not exist.
Connection Settings
Network connections and access permissions will likely vary between a Web request and a CLI call. This is due to two major factors: PHP will be running as a different user, and will likely be interpreted as connecting from a slightly different IP.
First and foremost, check the MySQL logs for errors. There you will likely find errors along the lines of Access denied for root@127.0.0.1:3306
. This is caused by the user only being granted access via a specific host. See what’s up by running the MySQL: SHOW GRANTS command.
This may even become more clear simply by connecting to MySQL via the CLI: # mysql --host=localhost --user=root --password=root database-name
Some testing of [mysql_connect](http://se2.php.net/mysql_connect)
may narrow down the issue for you:
function testConn(string $host) {
echo "\n\n MySql (".$host.") :\n";
$link = mysqli_connect($host, DB_USER, DB_PASS, DB_NAME);
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;
mysqli_close($link);
}
testConn(DB_HOST);
testConn('localhost');
testConn('127.0.0.1');
testConn('mydomain.com');
testConn('localhost:3306');
testConn('127.0.0.1:3306');
Environment Variables
Other differences in config and environment variables can be fairly difficult to track down. The best place to start would be comparing the results of phpinfo();
.