Search code examples
phpcroncommand-line-interfacerequire

PHP require() or include() stops the script without errors


I have this code:

echo "1 - is_readable: " . is_readable("/var/www/docroot/wp-load.php") . "\r\n";
echo "2 - file_exists: " . file_exists("/var/www/docroot/wp-load.php") . "\r\n";
echo "3 - before require\r\n";
require("/var/www/docroot/wp-load.php");
echo "4 - after require\r\n";

But the output is strange:

1 - is_readable: 1
2 - file_exists: 1
3 - before require

This situation appears when I start script from CLI or CRON, when I start it directly in browser - all is fine.

What is happened echo 4 doesn't display? Also I've tried to require another file, result is the same.

upd. task in crontab:

*/1 * * * * root php -f /mypath/fetch_data.php >> /mypath/results.out.log 2>&1

Solution

  • If you look at the wp-load.php file. It has below line

    error_reporting( E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR );
    

    This basically disables all the error reporting that you want. So edit the file and comment it and add

    error_reporting(E_ALL);
    

    Then you will know what the issues is. Also not all php files are compatible with CLI as they use some code that may only be valid when running under a web context.

    So if you are not able to fix the error in CLI, you can run the curl call to do the migration

    */1 * * * * root curl http://localhost/path/to/url
    

    Issue with this is that you will not get logs but only the output that your script gives. Also in case your scripts runs for long then you will need to add set_time_limit(0)

    https://www.php.net/manual/en/function.set-time-limit.php