Skip to content

Running PHP Scripts from Cron Jobs

Cron jobs allow you to schedule tasks to run automatically at specific intervals. On ruachost.com, you can use cron jobs to execute PHP scripts for tasks such as sending emails, cleaning up databases, or updating content.

  • Automate repetitive tasks.
  • Ensure scripts run consistently without manual intervention.
  • Improve efficiency for background processes (e.g., backups, reports).

This method simulates a web request to your script.

Terminal window
curl http://example.com/script.php

or

Terminal window
wget -q -O /dev/null http://example.com/script.php
  • Useful if your script depends on running through the web server.
  • Executes the script as if a user visited the URL.

Method 2: Using the PHP Command-Line Interpreter

Section titled “Method 2: Using the PHP Command-Line Interpreter”

Run the script directly with PHP:

Terminal window
/usr/local/bin/php -q ${HOME}/public_html/script.php
  • Faster than curl/wget because it bypasses the web server.
  • The -q option suppresses HTTP headers.
  • Recommended for scripts that don’t rely on web server context.

Method 3: Running from a Specific Directory

Section titled “Method 3: Running from a Specific Directory”

If your script uses relative paths, you may need to change to the correct directory first:

Terminal window
cd ${HOME}/public_html/; /usr/local/bin/php -q script.php
  • Ensures included files and relative paths resolve correctly.

If your script requires special configuration:

Terminal window
/usr/local/bin/php -c ${HOME}/php.ini ${HOME}/public_html/script.php

The -c option specifies a custom php.ini.

  • Useful for overriding default PHP settings.
  1. Log in to cPanel.
  2. Go to Advanced → Cron Jobs.
  3. Enter the command (examples above).
  4. Set the schedule (e.g., every 5 minutes, daily, weekly).
  5. Save the cron job.
  • Test scripts manually before scheduling.

  • Use absolute paths to avoid errors.

  • Log output to a file for debugging:

    Terminal window
    /usr/local/bin/php -q ${HOME}/public_html/script.php >> ${HOME}/cron.log 2>&1
  • Avoid running resource‑intensive scripts too frequently.