Knowledgebase

Running PHP from cronjob

Running PHP scripts from a cron job is a common task, especially in web development. Here's how you can set up a PHP script to run as a cron job:

  1. Create the PHP Script:

    First, create the PHP script you want to run. For example, let's say you have a script called myscript.php.

    php

 

  • <?php // Your PHP code here echo "This is my PHP script running from a cron job."; ?>
  • Make the Script Executable (if necessary):

    In some cases, you might need to make the script executable. You can do this using the following command:

    bash
  • chmod +x myscript.php
  • Set Up the Cron Job:

    Open your terminal and type:

    bash
  • crontab -e

    This opens the crontab file for editing.

  • Schedule the Cron Job:

    Add a new line to your crontab file in the following format:

    plaintext

 

* * * * * /path/to/php /path/to/myscript.php
  • The five asterisks represent the schedule (minute, hour, day of the month, month, day of the week).
  • /path/to/php should be replaced with the actual path to your PHP binary. You can find this by running which php in your terminal.
  • /path/to/myscript.php should be replaced with the actual path to your PHP script.

For example, if you want to run the script every day at 2:30 PM, you'd use:

plaintext
  1. 30 14 * * * /path/to/php /path/to/myscript.php
  2. Save and Exit:

    Save the file and exit the editor. In most cases, this is done by pressing Ctrl + X, then Y to confirm changes, and Enter to exit.

Your PHP script will now be executed according to the schedule you specified in the crontab. If there are any output or error messages, they will be emailed to the user account associated with the cron job. If you want to capture the output to a file, you can do so by appending >> /path/to/logfile.log 2>&1 at the end of the cron job line.

Remember that the user running the cron job must have permission to execute both PHP and the script file. Additionally, make sure to handle any file paths or dependencies in your PHP script properly to ensure it runs correctly in the cron environment.

 
  • 0 Users Found This Useful
Was this answer helpful?