How do I run my PHP script as a scheduled (cron) task?


Automating tasks is a fundamental aspect of efficient web management. For web hosting, this often involves scheduling PHP scripts to run automatically at predefined intervals. These scheduled tasks are commonly known as "cron jobs."

Cron jobs are incredibly useful for a variety of purposes, such as:

  • Cleaning up temporary files or old database entries.
  • Generating reports or sending out newsletters.
  • Processing queues or background tasks.
  • Performing regular backups or data synchronization.

This article will guide you through the process of setting up your PHP scripts to run as scheduled cron tasks on your EncodeDotHost hosting package.

Understanding the Cron Command Structure

A cron command is essentially a command-line instruction that your server executes. For a PHP script, the command typically follows this structure:

/path/to/php/interpreter /path/to/your/script.php argument1=value1 argument2=value2

Let's break down each part:

Path to the PHP Interpreter

This specifies which PHP version should be used to execute your script. On EncodeDotHost servers, we provide multiple PHP versions. The default path often points to a symbolic link to the recommended version.

  • PHP 7.4: /usr/bin/php74
  • PHP 8.2: /usr/bin/php82
  • PHP 8.3: /usr/bin/php83
  • PHP 8.4: /usr/bin/php84

Always use the specific interpreter path if your script requires a particular PHP version.

Path to Your PHP Script

This must be the absolute path to your PHP script on the server. An absolute path starts from the root directory of the server (e.g., /home/). You can usually find this path in your hosting control panel or by using a PHP function like __DIR__ or $_SERVER['DOCUMENT_ROOT'] within a test script.

A common structure for a script located in your public web directory might look like this:

/home/sites/yoursitename.com/public_html/cron.php

Replace yoursitename.com with your actual domain name.

Arguments to Be Passed to the Script

You can pass arguments to your PHP script directly from the command line. These arguments are accessible within your PHP script via the $argv global array.

For example, if your cron command includes task=tidy owner=1:

/usr/bin/php /home/sites/yoursitename.com/public_html/cron.php task=tidy owner=1

Inside cron.php, you would access these like so:

<?php
// The $argv array contains all command-line arguments
// $argv[0] is always the script name itself
// $argv[1] would be "task=tidy"
// $argv[2] would be "owner=1"

// A simple way to parse arguments:
$args = [];
foreach ($argv as $key => $value) {
    if ($key === 0) continue; // Skip script name
    if (strpos($value, '=') !== false) {
        list($argName, $argValue) = explode('=', $value, 2);
        $args[$argName] = $argValue;
    } else {
        $args[] = $value; // For arguments without an '='
    }
}

// Example usage:
if (isset($args['task']) && $args['task'] === 'tidy') {
    // Perform tidy-up operations
    echo "Tidying up completed!\n";
}

if (isset($args['owner'])) {
    echo "Owner ID: " . $args['owner'] . "\n";
}

// Note: When run via cron, output goes to cron log or email
// unless redirected. Newlines (\n) are important for readability in logs.
?>

This differs from accessing parameters via a web browser (e.g., http://yoursitename.com/cron.php?task=tidy&owner=1), where they are available in the $_GET or $_REQUEST superglobals.

Putting It All Together (Full Example)

Here's a complete example of a cron command you might enter into your hosting control panel to run a script daily:

/usr/bin/php83 /home/sites/yourdomain.com/public_html/scripts/daily_report.php --env=production

This command instructs the server to execute daily_report.php using PHP 8.3, passing --env=production as an argument.

Setting Up the Cron Job in Your Control Panel

The exact steps to add a cron job vary slightly depending on your hosting control panel (e.g., cPanel, Plesk, custom panels). Generally, you will look for a section named "Cron Jobs," "Scheduled Tasks," or similar. Within this section, you'll typically configure:

  • Command: The full command line as constructed above.
  • Schedule: Define how often the command should run (e.g., daily, hourly, specific times). This is usually done using a series of dropdowns or a cron expression (e.g., 0 0 * * * for midnight daily).

Important Considerations for Cron Jobs

  • Absolute Paths are Crucial: Always use full absolute paths for both the PHP interpreter and your script. Relative paths will almost certainly fail.
  • File Permissions: Ensure your PHP script has appropriate file permissions (e.g., 644 or 755) to be readable and executable by the server.
  • Output and Logging: By default, cron job output (anything echoed or printed by your script) is often emailed to the account owner. For long-running scripts or to avoid excessive emails, you can redirect output to a log file:
    /usr/bin/php /path/to/your/script.php > /path/to/your/log/file.log 2>&1
    

    The > /path/to/your/log/file.log redirects standard output, and 2>&1 redirects standard error to the same log file. To suppress all output, redirect to /dev/null:

    /usr/bin/php /path/to/your/script.php > /dev/null 2>&1
    
  • Error Handling: Implement robust error handling and logging within your PHP script itself. This will help you diagnose issues if the cron job fails silently.
  • Time Zones: Cron jobs run based on the server's time zone. Be aware of this if your script's logic depends on specific times relative to a different time zone.
  • Resource Usage: Be mindful of the resources your script consumes. Long-running or resource-intensive scripts might impact server performance or hit hosting limits.

By following these guidelines, you can effectively schedule and manage your PHP scripts as cron jobs, automating routine tasks and enhancing the functionality of your website.


Was this answer helpful?

One email a month. Endless business benefits.

Don't miss out on WMTWWFY — the newsletter that keeps your website fast, safe, and visible.

« Back
Spinner
aluminium-anthropoid Security Check