PHP · PHP Advanced

PHP CLI and Cron Jobs

Run this in the Online PHP compiler

Welcome to the efficient world of PHP Command Line Interface (CLI) and automation with cron jobs. PHP isn't just for web applications; it's also a powerful tool for scripting and automation tasks. Cron jobs allow you to automate these scripts at scheduled intervals.

Understanding PHP CLI

PHP CLI is a way to run PHP scripts from the command line. Unlike web scripts, CLI scripts don't run under a web server and don't need to output HTML. They are ideal for background tasks and automation.

Writing a PHP CLI Script

Here’s a basic PHP CLI script example:

Script (sendEmails.php):

#!/usr/bin/env php

Make your PHP file executable:

chmod +x sendEmails.php

Understanding Cron Jobs

Cron jobs are scheduled tasks on Unix-like systems. They're perfect for running PHP scripts at regular intervals, such as daily reports, regular data syncs, or email campaigns.

Setting Up a Cron Job

  • Open your crontab file:
crontab -e
  • Add a line to run your PHP script at scheduled intervals:
* * * * * /path/to/php /path/to/your/sendEmails.php

This example runs the script every minute. Adjust the cron schedule according to your needs.

Exercise

Create a PHP CLI script and set it up as a cron job:

  • Write a PHP script that does a simple task, like writing a log entry to a file.
  • Make the script executable and test it from the command line.
  • Schedule a cron job to run your script at regular intervals.

Hints for the Exercise:

  • To edit the cron schedule, understand the syntax: minute, hour, day of month, month, day of week.
  • Ensure the PHP binary's path is correct in your cron job (which php in the terminal gives you the path).
  • Test your PHP script manually in the CLI before scheduling a cron job.

Conclusion

You've just unlocked a new level of automation by combining PHP CLI with cron jobs. These tools open a myriad of possibilities for automated tasks in your PHP projects. Remember, with great power comes great responsibility - use cron jobs judiciously to enhance efficiency without overloading your server. Happy automating!

This website uses cookies to ensure you get the best experience on our website.