How To Detect If PHP Script Is Run From Cron Or Command Line?

Published September 1, 2024

Problem: Identifying PHP Script Execution Source

Knowing if a PHP script is running from a cron job or the command line can be tricky. This information helps you change how the script works and fix problems.

Solution: PHP Code to Detect Execution Source

Basic Implementation

To detect the execution source of a PHP script, you can use conditional statements that check the SAPI name and environment variables. Here's a basic implementation:

function getExecutionSource() {
    if (php_sapi_name() === 'cli') {
        if (isset($_SERVER['TERM'])) {
            return 'Manual CLI execution';
        } else {
            return 'Cron job execution';
        }
    } else {
        return 'Web server execution';
    }
}

$executionSource = getExecutionSource();
echo "This script is running from: $executionSource";

This function uses the php_sapi_name() function to check if the script is running from the command line interface (CLI). If it is, it then checks for the TERM environment variable to distinguish between manual CLI execution and cron job execution.

Tip: Debugging Execution Source

To debug and verify the execution source, you can add additional logging or output. For example:

function getExecutionSource() {
    $sapi = php_sapi_name();
    $term = isset($_SERVER['TERM']) ? $_SERVER['TERM'] : 'Not set';

    echo "SAPI: $sapi\n";
    echo "TERM: $term\n";

    // Rest of the function...
}

This will print out the SAPI name and TERM value, helping you understand how the script is determining the execution source.

Handling Different Execution Scenarios

Here's how to handle different execution scenarios:

  1. Web server execution:

    if (php_sapi_name() !== 'cli') {
    echo "This script is running from a web server.";
    // Add web server-specific code here
    }
  2. Manual command line execution:

    if (php_sapi_name() === 'cli' && isset($_SERVER['TERM'])) {
    echo "This script is running from a manual CLI execution.";
    // Add manual CLI-specific code here
    }
  3. Cron job execution:

    if (php_sapi_name() === 'cli' && !isset($_SERVER['TERM'])) {
    echo "This script is running as a cron job.";
    // Add cron job-specific code here
    }

By using these conditional statements, you can adapt your script's behavior based on its execution source. For example, you might want to send notifications only when the script runs as a cron job:

function sendNotification() {
    // Code to send notification
}

if (php_sapi_name() === 'cli' && !isset($_SERVER['TERM'])) {
    // Only send notification if running as a cron job
    sendNotification();
}

This approach allows you to control when certain actions are performed, such as sending emails or posting to social media, based on how the script is executed.