Home » Php » PHP include in a cron job

PHP include in a cron job

Posted by: admin July 12, 2020 Leave a comment


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

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?

How to&Answers:

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.


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.


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:


/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');


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