Skip to content

Running a PHP script with a cron job

A PHP script can be started on a schedule in two ways: with the PHP binary in your server's crontab, or through its address, which a service such as Cronjob.de calls from outside. Which one fits depends on whether you can get to the crontab. For both, this page shows what the call looks like and what the script itself needs to run reliably.

Option 1: PHP directly in the crontab

If you have SSH access to your server, add a line with crontab -e. This one starts the script every 10 minutes and writes output and error messages to a log file:

*/10 * * * * /usr/bin/php /var/www/project/cron/cleanup.php >> /var/www/project/cron/cleanup.log 2>&1

which php shows where PHP lives. If several versions are installed, the binary is often called php8.3 or similar. Use the same version the website runs on, otherwise extensions may be missing. How to edit the crontab and check whether a job ran is covered in Set up a cron job on Linux.

The command line is not the web server

In the crontab, PHP runs as a command line program (CLI). A script that works in the browser behaves differently there in a few places:

Crontab (CLI)Called through the address
Time limitnone, max_execution_time is 0your host's setting, plus how long the caller waits
Working directoryusually the user's home directorythe script's directory
php.inioften a separate file for the CLI, php --ini shows itthe web server's
Userthe owner of the crontabthe web server's user, e.g. www-data
Parameters$argv$_GET and $_POST
$_SERVER['HTTP_HOST']not setset

Relative paths are what trips scripts up most often. So write includes relative to the script, then the starting directory does not matter:

require __DIR__ . '/../config.php';

Calling the address from the crontab

If the script needs the web server, for example because it belongs to an application that only works through its URLs, call the address with curl. -f turns a status of 400 or above into an error, and -sS then prints only the error message:

*/10 * * * * curl -fsS --max-time 120 "https://your-site.com/cron/cleanup.php?key=…" > /dev/null

Option 2: Calling the script through its address

Many shared hosting plans have no crontab, only a few cron jobs or a coarse interval. Then you put the script into the web directory and a service calls its address on a schedule. To the script this is an ordinary page request, as if you had opened the address in a browser.

At Cronjob.de you enter the address and set the schedule, as a cron expression such as */10 * * * * or in your own words. Every call then appears in the log with status code and runtime. From Plus we also store your script's response, up to 5,000 characters for the latest call.

A status of 400 or above, an address that cannot be resolved, a dropped connection and the check page of a protection service such as Cloudflare all count as errors. A timeout only counts as an error if you switch that on in the cron job's “Success check” tab (from Plus). From Plus, Cronjob.de can notify you by email when something fails.

Our calls carry the user agent Cronjob.de (+https://www.cronjob.de/bot). If a firewall or security plugin blocks the call, the page about our identifier lists our IP addresses and examples for an exception.

Preparing the script to be called from outside

Protect it with a key

Anyone can call an address in the web directory, search engines and bots included. So the script should only do its work with a secret key and stop with 403 otherwise:

<?php
$secret = 'put-a-long-random-string-here';
if (!isset($_GET['key']) || !hash_equals($secret, (string) $_GET['key'])) {
    http_response_code(403);
    exit('Access denied');
}

It is then called as https://your-site.com/cron/cleanup.php?key=…. php -r 'echo bin2hex(random_bytes(20));' or any password generator produces a usable key. Instead, you can also protect the folder with a user name and password via .htaccess. Enter both in the cron job's fields for them, not in the address.

Return a clear result

What counts for the caller is the HTTP status code. If the script dies with an exception, depending on the PHP settings it may still return status 200, and the run looks successful. So catch errors, answer with 500 and print a fixed word at the end:

try {
    $count = cleanup();
    echo "OK: $count items done";
} catch (Throwable $e) {
    http_response_code(500);
    echo 'Error: ' . $e->getMessage();
}

If OK is in the response, the script got to the end. From Plus you can switch on in the “Success check” tab that a typical PHP message such as “Fatal error” in the response counts as an error, even with status 200. In Unlimited you can also set which text the response must contain, for example exactly this OK.

Stay under the time limit

A call through the address has two limits: max_execution_time at your host and how long the caller waits. Cronjob.de waits 45 seconds on the free plan, 60 on Plus and 90 on Unlimited, up to 5 minutes for single cron jobs there. Split bigger tasks into portions: each run does one part and the next one carries on from there. The example below shows what that looks like.

With ignore_user_abort(true) and set_time_limit(300) a script keeps working at many hosts after the caller has hung up. Whether it then finished is no longer visible in the log, though.

Rule out overlapping runs

If a run takes longer than the gap to the next one, two copies work on the same data at the same time. flock locks a file while the script runs and releases it on its own, even if the script crashes:

$lock = fopen(__DIR__ . '/cleanup.lock', 'c');
if (!$lock || !flock($lock, LOCK_EX | LOCK_NB)) {
    exit('Still running');
}

The second call then ends right away with status 200 and “Still running” in the response.

Scripts built only for the command line

Some scripts quit when they are not started from the command line (a check for php_sapi_name() === 'cli'), or read their options from $argv. Such scripts only run in the crontab unless you change the code. Many systems ship their own cron address for calls from outside, for example WordPress, Nextcloud and Matomo. How to set them up is in the guides.

Example: cleaning up a MySQL table every night

A service outside your server cannot run an SQL statement directly. You wrap it in a PHP script and the cron job calls the script. This one deletes entries older than 90 days in portions of 5,000 rows, so the table is never locked for long. It stops after 30 seconds at most, and the next run takes care of the rest.

<?php
// cron/cleanup-log.php
$secret = 'put-a-long-random-string-here';
if (!isset($_GET['key']) || !hash_equals($secret, (string) $_GET['key'])) {
    http_response_code(403);
    exit('Access denied');
}

$lock = fopen(__DIR__ . '/cleanup-log.lock', 'c');
if (!$lock || !flock($lock, LOCK_EX | LOCK_NB)) {
    exit('Still running');
}

header('Content-Type: text/plain; charset=utf-8');
try {
    $db = new PDO('mysql:host=localhost;dbname=shop;charset=utf8mb4', 'user', 'password',
                  array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    $until = time() + 30;
    $deleted = 0;
    do {
        $n = $db->exec('DELETE FROM log WHERE created < NOW() - INTERVAL 90 DAY LIMIT 5000');
        $deleted += $n;
    } while ($n === 5000 && time() < $until);
    echo "OK: $deleted rows deleted";
} catch (Throwable $e) {
    http_response_code(500);
    echo 'Error: ' . $e->getMessage();
}

Ideally take the credentials from the configuration your application already has instead of writing them into the script a second time. Open the address once in a browser. If it says “OK: … rows deleted”, create a cron job for it at Cronjob.de, for example daily at 3:30 am (30 3 * * *). If the backlog is big at first, let it run hourly for the first few days.

MySQL and MariaDB also have their own scheduler, the Event Scheduler (CREATE EVENT). Whether you may use it is up to your host, and if a run fails, that only shows up in the database server's error log.

Common questions

Why does my PHP script work in the browser but not as a cron job?
In the crontab it is usually down to the differences from the command line: a relative path, a different PHP version or missing permissions. When the address is called, a firewall or bot protection often rejects the automated request, which shows up as status 403. The troubleshooting guide goes through every cause in order.
How do I test the cron job without waiting for the schedule?
For the crontab, run the same command in the terminal as the user who owns the crontab, for example with sudo -u www-data /usr/bin/php /var/www/project/cron/cleanup.php. At Cronjob.de the “Execute job now” button in the cron job list starts a call right away.
Should the crontab use php, curl or wget?
php starts the script directly, without a web server and without a time limit. curl and wget call the address, so the script runs as it does in the browser, with the web server's settings and limits. If the script belongs to an application that only works through its URLs, use curl.

Have your PHP scripts called on a schedule

Five cron jobs are free forever at Cronjob.de, no credit card. For the first 14 days you can try everything, including failure emails and your script's stored response.

Start for free See pricing