Running PHP scripts from cron: paths, output and common mistakes

Write PHP scripts that run reliably from cron: the PHP binary path, working directory, includes, time limits, locking and logging.

Guide2 min readLast updated
On this page
  1. 1. Use the full PHP path
  2. 2. Don’t rely on the working directory
  3. 3. No web variables
  4. 4. Stop overlapping runs
  5. 5. Log what happens
  6. 6. Keep cron scripts out of public reach
  7. Alternative: calling a URL

Scripts that work in a browser often fail under cron, because the environment is different.

1. Use the full PHP path

/usr/local/bin/php /home/USERNAME/domains/yourdomain.co.uk/public_html/tasks/run.php

To confirm the PHP path and version cron uses, create a one-off job:

which php > /home/USERNAME/cron-test.txt; php -v >> /home/USERNAME/cron-test.txt

Read the file in the File Manager, then delete the job.

2. Don’t rely on the working directory

Cron doesn’t run from the script’s folder. Build paths from the script’s own location:

<?php
require __DIR__ . '/../config/bootstrap.php';

3. No web variables

$_SERVER['HTTP_HOST'], $_GET and sessions don’t exist. Pass settings as arguments instead:

/usr/local/bin/php /path/to/run.php --task=cleanup

4. Stop overlapping runs

If a job can take longer than its interval, prevent two copies running at once:

<?php
$lock = fopen(__DIR__ . '/run.lock', 'c');
if (!flock($lock, LOCK_EX | LOCK_NB)) {
 exit(0); // previous run still going
}
// ... work ...

5. Log what happens

/usr/local/bin/php /path/to/run.php >> /home/USERNAME/logs/run.log 2>&1

Include timestamps in your output so the log is useful.

6. Keep cron scripts out of public reach

Put them outside public_html, or block web access, so a visitor can’t trigger them by URL.

Alternative: calling a URL

If a job must run through the web server:

curl -fsS https://yourdomain.co.uk/cron.php?key=LONG_SECRET >/dev/null

Protect the URL with a secret key.

Prefer to follow along?

New to Traxio? The PHP hosting page lists the PHP versions, database and tools every account gets.

Spotted something out of date or unclear? Tell us and we’ll fix it.

Keep going