Set the working directory for PHP scripts that run via cron

There are fundamental differences between PHP scripts that are run by a web request, and those that are run from the command line. One of the main ones is that the environment settings will be completely different, including the path. Every few years I forget this and it comes back to bite me.

Generally I use relative paths for require_once() and similar functions. This is because it makes the code more portable when moving to a different storage location or a different server (e.g. working with development and live servers). The downside is that the relative paths are likely to point to completely the wrong location for scripts that are called via the command line. There are various reasons for wanting to run PHP scripts on the command line, one of the most common being for cron jobs. Of course they can be run using wget or curl or suchlike, but that causes extra overhead with the web server, not to mention potential problems with timeouts and so on.

To avoid this kind of problem, when writing a script that will be run as a cron job, I now always put the following code at the top:

chdir( __DIR__ );

This changes the current working directory to the path of the script, which means that require_once() will work as expected. In addition, I strongly recommend writing cron scripts that do not produce any output unless there is an error, and making sure that your cron settings will notify you by email of any output produced. This follows standard best practice guidelines for cron jobs. It always surprises me how many cron jobs I see where the author couldn’t be bothered to differentiate between correct behaviour and errors, and then redirects all output to /dev/null because they are sick of being bombarded with emails.


Add new comment