7
votes

I'm trying to setup a PHP file as a cron job, where that PHP file includes other PHP files.

The file itself is located at /var/www/vhosts/domain.com/httpdocs/app/protected/classes/cron/runner.php

The include file is at /var/www/vhosts/domain.com/httpdocs/app/protected/config.php

How do I include that config file from runner.php? I tried doing require_once('../../config.php') but it said the file didn't exist.. I presume the cron runs PHP from a different location or something.

The cron job is the following..

/usr/bin/php -q /var/www/vhosts/domain.com/httpdocs/app/protected/classes/cron/runner.php

Any thoughts?

4

4 Answers

16
votes

Your cron should change the working directory before running PHP:

cd /var/www/vhosts/domain.com/httpdocs/app/protected/classes/cron/ && /usr/bin/php -q runner.php

Note that if the directory does not exist, PHP will not run runner.php.

2
votes

You should use an absolute path. The cron is probably not running the script from within the directory in which it resides.

I recommend using:

require_once( dirname(__FILE__) '../../config.php )

__FILE__ is a special constant that refers to the file you're in. dirname(...) will give you the directory, which will evaluate to the absolute path of the file you wish to include.

1
votes

Is classes or cron a symbolic link? I seem to remember that php evaluates the real path instead of the symbolic path.

Consider the following directory tree:

/target/index.php

/path/sym -> /target

if you were to execute php index.php from /path/sym then the statement require_once('../require.php'); would evaluate to require_once('/require.php'); not require_once('/path/require.php');

1
votes

You can change the working directory inside your PHP script to the location of that script: chdir(__DIR__); (or, if your PHP version is before 5.3: chdir(dirname(__FILE__));) Then you can do: require_once('../../config.php')