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.
On this page
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.phpTo 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.txtRead 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=cleanup4. 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>&1Include 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/nullProtect the URL with a secret key.
Prefer to follow along?
- Schedule a task with a cron job
Intermediate · 20 min
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.