Issue
I have a script, let's call it mainfile.php that has an include in it for a file in the same directory. I am including it as follows:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once './myincludefile.php';
?>
If I do the following:
nohup php mainfile.php >/dev/null
It runs without any problems. However, if turn this into a cron job, I get the following message (in my mail spool):
PHP Warning: require_once(./myincludefile.php): failed to open stream: No such file or directory in /home/code/mainfile.php on line 5
PHP Fatal error: require_once(): Failed opening required './myincludefile.php' (include_path='.:/usr/share/pear:/usr/share/php') in/home/code/mainfile.php on line 5
Any ideas?
Solution
That's because the current working directory of the script is not the same when called via cron. (I assume it is /
, the root directory)
Change the require_once
to:
require_once __DIR__ . '/myincludefile.php';
__DIR__
will always contain the directory where the current script is located - not the current working directory. That´s why it is handy to build relative paths.
Answered By - hek2mgl Answer Checked By - David Marino (WPSolving Volunteer)