Running Cronjob from a specific directory

John Cogan picture John Cogan · Jul 12, 2013 · Viewed 9.1k times · Source

I created a php script for generating RSS feeds which is to eventually be run via a Cronjob.

All the php files and the resulting RSS xml will be within a sub folder in a website. The php script runs fine on my local dev if I use terminal or the browser while within the same directory on my local development machine.

e.g. php /Library/WebServer/Documents/clientname/siteroot/rss/dorss.php

works fine as does navigating to the dorss.php file in Chrome.

The CronJob has executed though with errors related to the fact that it cannot find the files specified with require_once() which are located in the same folder as rss or in a subfolder of that.

Long story short I need to have the Cronjob run from within the same directory as the dorss.php file so it can reference the include files correctly.

My knowledge on setting up a cronjob is VERY limited so I wanted to ask if this is at all possible (Change directory before running command) to do this on the same command line of the crontab or if not how can it be achieved please?

The current cronjob command is

0 0,6,12,18 * * * /usr/bin/php /var/www/vhosts/clientname/stagingsite/rss/dorss.php

TIA John

Answer

António Almeida picture António Almeida · Aug 13, 2015

You can change directory to the one you want and then run the php from that directory by doing this:

cd /var/www/vhosts/clientname/stagingsite/rss/
&&
/usr/bin/php dorss.php

It's easier than creating bash scripts, here is the result:

0 0,6,12,18 * * * cd /var/www/vhosts/clientname/stagingsite/rss/ && /usr/bin/php dorss.php