yenren
yenren

Reputation: 505

Correct Cron job command in order for PHP require() to work

I'm on GoDaddy shared hosting. In my cron job PHP script, I use require() to include some other files. The cron job PHP script works fine when I use it manually (via entering its url to the address bar), but when the cron job is performed, the cron script works fine, except it can't find the required files.

I have the following cron command:

/usr/local/bin/php -q /home/username/public_html/domainname/cron/script.php >/dev/null 2>&1

I read here that one option is to use full paths in require(). Another option is to modify the cron command, which is what I want to learn. My question is how to modify the above cron command so that my require() in the cron script will work (without using full paths).

Thanks.

Upvotes: 0

Views: 220

Answers (1)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21671

This is probably the easiest way to fix it.

chdir(dirname(__FILE__)); //its been a while but I think __FILE__ works better with bind mounts and symlink but don't quote me on that.
//chdir(__DIR__);

I can't quite remember, but I think I had to use this one time for a wordpress site, that I made a cron job for. If I remember correctly it had some relative directories, from 3rd party plugins etc...

Other wise you can use __DIR__ before your files.

I never use relative directories, I either use a constant

 define('BASE_DIR', __DIR__); //or something else besides __DIR__

Or I just use __DIR__ and never have these kinds of issues. I like knowing exactly where my files are.

require __DIR__.'/somefile.php';
require BASE_DIR.'/somefile.php';

This is not really a PHP issue, its more an issue of how cron calls the PHP file, because the relative paths will be relative to the location of the crontab file.

Summery

That said about using __DIR__ I know from my own experience, you can't control how third parties include files, so chdir is probably the only workable solution in that case.

Hope it helps.

Upvotes: 2

Related Questions