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.
Why Use Cron Jobs for PHP?
-
Automate repetitive tasks.
-
Ensure scripts run consistently without manual intervention.
-
Improve efficiency for background processes (e.g., backups, reports).
Methods to Run PHP Scripts from Cron Jobs
Method 1: Using curl or wget
This method simulates a web request to your script.
Bash
curl http://example.com/script.php
or
Bash
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
Run the script directly with PHP:
Bash
/usr/local/bin/php -q ${HOME}/public_html/script.php
-
Faster than curl/wget because it bypasses the web server.
-
The
-qoption suppresses HTTP headers. -
Recommended for scripts that don’t rely on web server context.
Method 3: Running from a Specific Directory
If your script uses relative paths, you may need to change to the correct directory first:
Bash
cd ${HOME}/public_html/; /usr/local/bin/php -q script.php
-
Ensures included files and relative paths resolve correctly.
Method 4: Using a Custom php.ini File
If your script requires special configuration:
Bash
/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.
Setting Up Cron Jobs in cPanel
-
Log in to cPanel.
-
Go to Advanced → Cron Jobs.
-
Enter the command (examples above).
-
Set the schedule (e.g., every 5 minutes, daily, weekly).
-
Save the cron job.
Best Practices
-
Test scripts manually before scheduling.
-
Use absolute paths to avoid errors.
-
Log output to a file for debugging:
Bash /usr/local/bin/php -q ${HOME}/public_html/script.php >> ${HOME}/cron.log 2>&1 -
Avoid running resource‑intensive scripts too frequently.