Overview
Some tasks should not run during a visitor's web request. Sending bulk notifications, importing data, generating reports and cleaning temporary files can take too long or fail after the user has left. Background execution separates these jobs from the response lifecycle.
Start with a CLI entry point
A command-line script can load the same application bootstrap as the web application, then call a focused service. Keep CLI commands explicit and validate their arguments. Use the intended PHP binary on hosting systems where multiple PHP versions are installed.
Schedule with cron
Cron is suitable for predictable recurring work such as nightly cleanup. Use absolute paths, a known working directory and a private log destination. Prevent overlapping executions with a lock or database lease when a job must not run concurrently.
Make jobs restartable
A long-running task should process bounded batches, record progress and tolerate interruption. Design each batch to be idempotent where possible. Store job status, attempts and failure reasons without logging credentials or sensitive payloads.
Avoid public trigger URLs
Do not expose a maintenance script as an unauthenticated web URL. Run it through CLI or protect it with strong authentication and network restrictions if a web trigger is unavoidable. Apply timeouts and resource limits appropriate to the job.
Official references
PHP command-line usage PHP CLI options
Use the CLI entry point
Background tasks should run through PHP CLI rather than a visitor's web request. Keep scripts outside the public document root and invoke them with the intended PHP binary and configuration.
*/5 * * * * /usr/bin/php /home/account/app/bin/cleanup.php >> /home/account/private/logs/cleanup.log 2>&1
On cPanel or managed hosting, select the correct PHP CLI path for the required version. Test the command manually as the same account that will run the scheduled job.
Make jobs safe to repeat
A cron job may overlap or run again after a timeout. Use a lock or database lease when overlap would be harmful. Process work in bounded batches, record progress and make each item idempotent where possible.
Monitor outcomes
Log start time, finish time, processed counts and failures. Alert on repeated failures or jobs that stop running. Do not log secrets or personal data. Set timeouts and memory limits appropriate to the task.
Avoid web-triggered maintenance
Do not expose cleanup, import or report scripts as public URLs without authentication and authorization. Prefer CLI execution. If a web-triggered administrative action is unavoidable, protect it with strong authorization, CSRF protection and rate limits.