You wrote bin/export-feed.php, ran php bin/export-feed.php over SSH, and the feed came out right. You added it to crontab for 04:15, and the next morning there's no feed, no error and no log. Or there is an error, Failed opening required 'vendor/autoload.php', from a script that worked five minutes ago.
Nothing is wrong with the script. Cron runs it with a different php binary, a different php.ini, a different working directory and almost no environment, and PHP is unusually sensitive to all four. This guide fixes each one with a crontab line you can build below, covers cPanel cron on shared hosting, and shows the route many PHP sites end up on: a web script behind a secret header, called on a clock from outside.
Two ways to run PHP on a clock
Every plain-PHP schedule comes down to one question: does the clock start a PHP CLI process on the server, or does it send an HTTP request to a script that PHP-FPM serves like any page? Laravel's and Symfony's schedulers are a layer on top of the first option, and long-running PHP workers are a third option most sites never need.
| Trigger | You need | Time limit | Timezone | When it fails |
|---|---|---|---|---|
| crontab + PHP CLI | SSH and a crontab | None, unless you add one | Server's | A log line, if you kept one |
| cPanel cron | A cPanel account | Your host's rules | Server's | An email per run, or none |
| Web script + external cron | A URL and a secret | Web timeouts (30 to 60 seconds by default) | Per schedule | Retries, then an alert |
| Framework scheduler | Laravel or Symfony, plus one of the above | Same as the trigger underneath | Per task | Framework hooks and logs |
Use the CLI when the job runs for minutes, touches local files, or the box is yours. Use the web trigger when you have no shell, the app runs on several servers or in containers, or you want someone to tell you when a run fails. Plenty of teams run both: crontab for the heavy nightly export, an HTTP schedule for the five-minute cache warm.
crontab with the PHP CLI: build the line that works
Open your crontab with crontab -e and add one line per job. If the five schedule fields are new to you, what is a cron job in Linux walks through them and the cron syntax cheat sheet has the common patterns. Then build the rest of the line here: pick your host and PHP version, type your script, and switch pieces on and off to see what each one does.
PHP crontab line builder
Debian / Ubuntu · 6 pieces
15 4 * * * cd /var/www/app && flock -n /tmp/export-feed.lock /usr/bin/php8.4 bin/export-feed.php >> /var/log/app/export-feed.log 2>&1
Run it the way cron will
Paste this over SSH before you save the crontab. It starts in your home directory with an empty environment, like cron does, so a missing variable or relative path fails now instead of at night.
cd ~ && env -i HOME="$HOME" PATH=/usr/bin:/bin /bin/sh -c 'cd /var/www/app && flock -n /tmp/export-feed.lock /usr/bin/php8.4 bin/export-feed.php >> /var/log/app/export-feed.log 2>&1'Paths are typical for each host. Confirm yours with command -v php on the server.
The default line looks like a lot for one script, but every piece is there because a PHP cron job broke without it. The next five sections go through them in the order they usually bite.
Call PHP by its full path
Cron's PATH is short, typically /usr/bin:/bin, so php in a crontab finds whatever lives there, which may not be the PHP you tested with. A server with several versions has several binaries, and your shell may resolve php through /usr/local/bin or an alias that cron never sees.
command -v php # what your shell runs
readlink -f "$(command -v php)" # the real binary behind the symlink
ls /usr/bin/php* # every version installed (Debian, Ubuntu)On Debian and Ubuntu each version installs a binary like /usr/bin/php8.4, and /usr/bin/php points to the default through update-alternatives. Write the versioned path in the crontab, so an upgrade that moves the default doesn't quietly change what runs at 04:15. As of November 2026 the supported branches are PHP 8.2 to 8.5; 8.2 gets its last security fixes on December 31, 2026.
The CLI reads a different php.ini
This is the one that makes "it works in the browser" useless as evidence. PHP-FPM, which served your test page, and the PHP CLI, which cron runs, are separate programs with separate ini files and different built-in rules.
- php.iniUsual culprit
- /etc/php/8.4/fpm/php.ini
- /etc/php/8.4/cli/php.ini
- max_execution_time
- 30 seconds (php.ini default)
- 0, no limit. The CLI always forces it
- memory_limit
- 128M
- -1 (no limit) in Debian and Ubuntu packages
- Runs asUsual culprit
- The pool user, often www-data
- Whoever owns the crontab
- Working directoryUsual culprit
- The script's own folder
- Your home directory. PHP never changes it
- EnvironmentUsual culprit
- Cleared (clear_env), plus the pool's env[] lines
- Cron's handful: HOME, LOGNAME, SHELL, a short PATH
- Request data
- $_GET, $_POST, HTTP_* headers in $_SERVER
- $argv and $argc. No HTTP_HOST, no REQUEST_URI
- Output
- The HTTP response
- stdout: mailed by cron, or into your log redirect
- OPcache
- On
- Off (opcache.enable_cli=0)
The PHP manual lists what the CLI overrides: max_execution_time is always 0, so a stuck run never times out on its own, and errors print as plain text. Debian's packaging also sets memory_limit = -1 in the CLI's php.ini, while the FPM one keeps 128M. That sounds generous until a runaway export eats the server's RAM instead of failing at a limit.
Check what cron's PHP actually loads, then pin the values the job depends on instead of trusting either file:
/usr/bin/php8.4 --ini # which php.ini and conf.d files load
/usr/bin/php8.4 -i | grep -E 'memory_limit|date.timezone|max_execution'
/usr/bin/php8.4 -m | grep -i -E 'intl|gd|pdo' # extensions the CLI has// top of bin/export-feed.php
ini_set('memory_limit', '512M');
date_default_timezone_set('Europe/Berlin');
set_time_limit(900); // the CLI's 0 becomes a 15-minute ceilingMissing extensions are the other classic. ext-intl or pdo_pgsql may be enabled in the FPM conf.d folder and not in the CLI one; php -m from the binary in your crontab settles it. OPcache is off in the CLI by default (opcache.enable_cli=0), and for a short cron run that's fine: the cache would die with the process anyway.
Cron starts in your home directory
The PHP CLI never changes into the script's folder, and cron starts every job in the crontab owner's home directory. So require 'vendor/autoload.php' in bin/export-feed.php searches your home directory and bin/, never the project root, and file_put_contents('feeds/today.xml', ...) writes into your home directory, or fails because ~/feeds doesn't exist.
Fix it twice. The cd /var/www/app && in the line makes relative paths behave like they did in your terminal, and building paths from __DIR__ inside the script makes them right no matter who starts it:
require __DIR__ . '/../vendor/autoload.php';
$out = dirname(__DIR__) . '/storage/feeds/today.xml';While you're thinking about files: cron runs the job as the crontab's owner, not as the web server's user. A feed written by your SSH user can be unreadable for www-data, and a cache folder created by www-data can be unwritable for the cron job. Put the line in the crontab of the user that owns the files, for example with sudo crontab -u www-data -e.
Cron has almost no environment
Cron sets SHELL=/bin/sh, HOME, LOGNAME and a minimal PATH, and that's about it (crontab(5)). Whatever you exported in .bashrc, and whatever the web server passes to PHP-FPM, isn't there. Scripts that read DATABASE_URL from the environment connect to nothing.
Load the configuration from the script itself. With vlucas/phpdotenv:
require __DIR__ . '/../vendor/autoload.php';
Dotenv\Dotenv::createImmutable(dirname(__DIR__))->load();
$dsn = $_ENV['DATABASE_URL'];createImmutable() fills $_ENV and $_SERVER, not getenv(). Real environment variables work the other way round: the ones you declare at the top of the crontab (APP_ENV=production on its own line) are readable with getenv(), but $_ENV stays empty because production php.ini files set variables_order = "GPCS", leaving out the E. And keep secrets out of the crontab itself; anyone who can read it can read them.
Send the output somewhere you'll read
Without a redirect, cron mails whatever the script prints to the crontab's owner, or to MAILTO if you set one. On most servers nobody reads that mailbox. >> /var/log/app/export-feed.log 2>&1 appends both stdout and PHP's warnings and fatal errors to one file; where cron logs are stored covers cron's own log, which tells you whether the line started at all.
Two details save a confused morning. Cron turns an unescaped % into a newline, so date +%F in a crontab must be written date +\%F (the builder escapes it for you). And make the script's exit code mean something: an uncaught exception or fatal error already exits with 255, but a job that catches its own errors should end with exit(1) so flock, timeout and heartbeat pings can tell success from failure.
Stop runs from piling up with flock
Cron starts the next run on time whether or not the last one finished. A feed export that usually takes four minutes and once takes twenty, on a five-minute schedule, ends up running four copies against the same database. flock -n prevents that: it holds a lock file while PHP runs, and a second run that can't get the lock exits right away with code 1. The kernel drops the lock when the process ends, crash or not, so there's no stale lock to clean up.
The same lock works from inside PHP, which also covers the web trigger later in this guide, where two HTTP calls can overlap:
$lock = fopen(sys_get_temp_dir() . '/export-feed.lock', 'c');
if (!flock($lock, LOCK_EX | LOCK_NB)) {
fwrite(STDERR, "Previous run still going, skipping.\n");
exit(0);
}
// ... the export; the lock is released when the script endsflock stops overlaps but not runs that hang forever, and with max_execution_time at 0 a stuck HTTP call or a deadlocked query will hold the lock until someone notices. Add timeout 15m in front of the PHP binary (it exits with 124 when it fires), or set_time_limit() in the script.
Pick crontab when the server is yours, the job may run for minutes, and someone reads the log. On a VPS, a systemd timer is the sturdier cousin: it catches up on runs missed during downtime and never overlaps itself; the Python guide's systemd section has the two files, and only ExecStart changes for PHP.
Shared hosting: the same line in cPanel cron
On shared hosting there's often no SSH, but there's a Cron Jobs page in cPanel. It's a form around the same crontab: cPanel's docs describe five boxes for minute, hour, day, month and weekday, and a Command box that takes everything else. Pick cPanel in the builder above and it splits the line that way.
- 1
Find the PHP binary for your site's version
cPanel servers with EasyApache 4 keep one binary per version, like
/opt/cpanel/ea-php84/root/usr/bin/php, and a barephpmay run a different version than your site. Your host's help pages list the exact path; if you have Terminal in cPanel,ls /opt/cpanel/ea-php*/root/usr/bin/phpshows them. - 2
Use absolute paths everywhere
The command runs from your home directory,
/home/<user>. cPanel's docs recommend absolute paths for the script, and the same goes for the log file and anything the script includes. - 3
Decide what happens to the output
cPanel emails each job's output to the address in the Cron Email box. Point the output at a log file, or end the command with
> /dev/null 2>&1to silence one job, as the docs suggest. Silence without a log or a heartbeat means failures go unnoticed. - 4
Leave room between runs
cPanel's docs warn to leave enough time for each job to finish before the next starts, and many hosts cap CPU time, processes or how often cron may run. Check your host's rules before you schedule anything every minute, and keep the
flockin the line.
The cPanel cron jobs guide covers the screen field by field, where cPanel keeps the logs, and the mistakes people make with it. If your host has no cron at all, or kills jobs that run too long, the next section is the way out.
Web-triggered PHP scripts: protect them with a secret header
A web trigger turns the job into a URL. PHP-FPM runs it like any page, so the script gets the same php.ini, extensions and environment as your site, and none of the CLI differences above apply. The cost is that the URL is public, so it needs a secret, and it lives inside the web server's time limits.
<?php
// public/cron/export-feed.php
declare(strict_types=1);
require dirname(__DIR__, 2) . '/vendor/autoload.php';
Dotenv\Dotenv::createImmutable(dirname(__DIR__, 2))->load();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
exit;
}
$secret = $_ENV['CRON_SECRET'] ?? '';
$given = $_SERVER['HTTP_X_CRON_SECRET'] ?? '';
if ($secret === '' || !hash_equals($secret, $given)) {
http_response_code(401);
exit;
}
ignore_user_abort(true); // keep going if the caller hangs up
set_time_limit(55); // stay under the proxy's 60-second timeout
try {
$count = App\Jobs\ExportFeed::run();
header('Content-Type: application/json');
echo json_encode(['ok' => true, 'exported' => $count]);
} catch (Throwable $e) {
error_log('export-feed failed: ' . $e->getMessage());
http_response_code(500); // the scheduler sees the failure
}hash_equals() compares in constant time, so the secret can't be guessed from response timing; the known secret goes first, the value from the request second. Generate one with php -r 'echo bin2hex(random_bytes(32)), PHP_EOL;' and keep it in .env, outside the document root.
The other half is the clock you're now running under. Each layer between the caller and your script has its own limit, and the shortest one wins:
30s
max_execution_time
php.ini default for web requests; on most Linux builds it counts CPU time, not waiting
60s
nginx fastcgi_read_timeout
Default; the gateway gives up and returns a 504
300s
Apache Timeout
Default, per the PHP manual
0
FPM request_terminate_timeout
Off by default; a pool may set one
ignore_user_abort(true) keeps the script running if the caller disconnects, and set_time_limit() gives this request its own budget, but neither moves the proxy's 60 seconds. For jobs that take longer, answer quickly and keep working: on PHP-FPM, fastcgi_finish_request() sends the response and lets the script continue, though it keeps an FPM worker busy the whole time, and the caller only learns the job started, not that it finished. Past a few minutes, push the work onto a queue and let a worker process it.
Two more habits keep a web trigger safe. Keep CLI-only scripts outside public/, or guard them with if (PHP_SAPI !== 'cli') { http_response_code(404); exit; }, so bin/export-feed.php can't be started by a crawler. And use the in-PHP flock() from the overlap section if a slow run could still be going when the next call arrives.
Call the script on a schedule from outside
With the script deployed, something has to call it. An external HTTP scheduler does that without a server of yours: it sends the POST with your header on a cron expression, in the timezone you pick, and keeps a record of every call.
- 1
Test the URL by hand
curl -i -X POST https://shop.example.com/cron/export-feed.php \ -H "X-Cron-Secret: $CRON_SECRET"A 200 with
{"ok":true}means the script runs. A 401 means the header or.envdoesn't match; a 405 means you sent a GET. - 2
Create the schedule
In Crontap, add a
POSTto the URL, add theX-Cron-Secretheader, set the cron to15 4 * * *, and pickAmerica/New_York(or any IANA zone) for this schedule. Runs follow that zone through daylight saving changes, whatever the server's clock says. - 3
Press Perform test
Perform test calls the URL right away and shows the status code, timing and response, so a wrong header or a fatal error shows up now instead of at 04:15.
- 4
Let failures reach you
New schedules retry 5xx responses, timeouts and network errors with exponential backoff and record every attempt. When the attempts run out, Crontap alerts you by email on every plan, or in Slack, Discord or Telegram on paid plans.
The honest trade-offs: the scheduler only calls your script, so the work is still bound by the web timeouts above, and the URL must stay reachable over HTTPS. The free Crontap plan covers two schedules or monitors at intervals down to one hour; paid plans go down to every minute. If your PHP site is WordPress, the same pattern replaces wp-cron: replace wp-cron with a real scheduler shows the DISABLE_WP_CRON setup.
Laravel, Symfony and long-running PHP workers
Frameworks don't remove cron; they collapse it to one line. Laravel's scheduler needs a single crontab entry that runs every minute, and the Laravel docs (13.x as of November 2026) put the schedule itself in routes/console.php, with withoutOverlapping() and onOneServer() for the problems flock solves here:
* * * * * cd /var/www/app && /usr/bin/php8.4 artisan schedule:run >> /dev/null 2>&1Everything in the crontab sections above still applies to that line, starting with the full PHP path. The Laravel cron jobs guide covers the scheduler, queues and the HTTP alternative in depth.
Symfony's Scheduler component works differently: schedules produce Messenger messages, and a worker started with php bin/console messenger:consume scheduler_default must keep running under Supervisor or systemd. ReactPHP, Workerman, Amp and Swoole can also run timers inside a long-lived PHP process. Both make sense when you already operate a PHP worker; adding one just to fire a nightly job means babysitting memory growth and restarts for something a crontab line does.
Know when a PHP job didn't run
A crontab job fails in two ways. Loud failures leave a trace: a fatal error in the log, a non-zero exit. Silent ones leave nothing: the server was rebuilt without the crontab, someone commented the line out, the host disabled cron for your account. A log can't show you a run that never started.
A heartbeat covers both. The job calls a URL when it succeeds, and Crontap alerts you if no call arrives within the period plus a grace window. The builder's Heartbeat piece adds a curl after &&, so it only fires on exit code 0. From PHP, you can also report failures the moment they happen:
$heartbeat = 'https://ping.crontap.com/<heartbeat-id>';
$ctx = stream_context_create(['http' => ['timeout' => 10]]);
try {
App\Jobs\ExportFeed::run();
@file_get_contents($heartbeat, false, $ctx);
} catch (Throwable $e) {
@file_get_contents($heartbeat . '/fail', false, $ctx); // alerts right away
throw $e;
}If a job still won't fire and you can't see why, cron job not running and the cron troubleshooting guide work through the rest of the list, from a stopped cron daemon to file permissions and throttled shared hosts.
FAQ
PHP cron job questions
- How do I run a PHP script as a cron job?
- Run crontab -e and add one line: the five schedule fields, a cd into the project, the PHP binary by its full path, the script, and a log redirect. For example: 15 4 * * * cd /var/www/app && flock -n /tmp/export-feed.lock /usr/bin/php8.4 bin/export-feed.php >> /var/log/app/export-feed.log 2>&1. Find the binary with command -v php on the server.
- Why does my PHP script work in the browser or terminal but not in cron?
- Cron runs a different PHP with a different setup. It may pick another php binary from its short PATH, the CLI reads its own php.ini (on Debian and Ubuntu, /etc/php/8.4/cli/php.ini instead of the fpm one), the working directory is your home folder, and none of your shell's environment variables exist. Use the full binary path, cd into the project, build file paths from __DIR__, and load your .env from the script.
- What is the path to PHP for a cron job?
- Run command -v php on the server and resolve symlinks with readlink -f. Debian and Ubuntu install versioned binaries like /usr/bin/php8.4, with /usr/bin/php pointing at the default through update-alternatives. On cPanel with EasyApache 4 each version has its own binary, such as /opt/cpanel/ea-php84/root/usr/bin/php; your host's docs list the exact path. Pin the versioned path so a PHP upgrade on the server doesn't change what cron runs.
- Does PHP CLI use a different php.ini than PHP-FPM?
- Usually, yes. Debian and Ubuntu ship /etc/php/<version>/cli/php.ini and /etc/php/<version>/fpm/php.ini, and their packages set memory_limit to -1 in the CLI file. The CLI also forces max_execution_time to 0, whatever php.ini says. Run php --ini to see which files the CLI loads, and compare with the Loaded Configuration File line of phpinfo() in the browser.
- How do I stop a PHP cron job from running twice at the same time?
- Wrap the command in flock -n with a lock file: flock -n /tmp/export-feed.lock /usr/bin/php8.4 bin/export-feed.php. If the previous run still holds the lock, the new one exits with code 1 instead of starting. Inside PHP you can do the same with fopen on a lock file and flock($handle, LOCK_EX | LOCK_NB). Both locks are released when the process ends, even after a fatal error.
- Where does the output of a PHP cron job go?
- Without a redirect, cron mails anything the script prints to the crontab's owner, or to MAILTO if you set it, and on most servers that mail is never read. Append >> /path/to/job.log 2>&1 to keep stdout and PHP's warnings in one file, and escape any % in the line as \% because cron turns an unescaped % into a newline.
- Why are my environment variables empty in a PHP cron job?
- Cron starts the command with only a few variables (HOME, LOGNAME, SHELL and a short PATH), so anything exported in your shell profile or set in the web server's pool is missing. Load the .env file from the script with a library such as vlucas/phpdotenv and a path built from __DIR__, or declare them at the top of the crontab. Variables from the crontab are real environment variables, so read them with getenv(): $_ENV stays empty when variables_order leaves out E, as the production php.ini does. phpdotenv's createImmutable() fills $_ENV and $_SERVER instead.
- How do I set up a PHP cron job on cPanel shared hosting?
- Open Cron Jobs in cPanel, fill in the Minute, Hour, Day, Month and Weekday boxes, and put the command in the Command box: the full path to your PHP binary, then the absolute path to the script, then a log redirect. Use the PHP binary path from your host's docs so the version matches your site. To stop the cron email for one job, end its command with > /dev/null 2>&1.
- Can I run a PHP cron job without SSH or crontab access?
- Yes. Put the job behind a URL on your site, protect it with a long secret sent in a header, and have an external scheduler call that URL on a cron schedule. The script runs inside PHP-FPM like any page, so keep each run under the web timeouts (30 seconds of max_execution_time by default, 60 seconds of nginx fastcgi_read_timeout) or hand the work to a queue.
- How do I protect a PHP cron URL from strangers?
- Require a secret header, such as X-Cron-Secret, compare it with hash_equals() against a value from the environment, and return 401 when it doesn't match. Accept only POST, keep the secret out of the query string where access logs would record it, and keep CLI-only scripts outside the document root. Apache can hide the Authorization header from PHP unless CGIPassAuth is on, which is why a custom header is the safer choice on shared hosting.
- Should I use Laravel's scheduler or plain crontab for PHP?
- If the app is Laravel, use its scheduler: one crontab line runs php artisan schedule:run every minute, and the schedule lives in routes/console.php with overlap and single-server locks built in. Plain crontab or an HTTP trigger fits scripts without a framework. The Laravel cron jobs guide covers the scheduler in depth.
- How do I get alerted when a PHP cron job fails or doesn't run?
- For a job behind a URL, Crontap retries 5xx responses, timeouts and network errors, records each attempt, and alerts you once the attempts are used up: by email on every plan, or in Slack, Discord or Telegram on paid plans. For a crontab job, ping a heartbeat URL when the script exits with 0, and its /fail URL from your error handler. Crontap alerts right away on /fail, and when no ping arrives within the period plus grace.
