Are you smart enough to detect is PHP execution from cli command line cron job?

Detect cli execution in PHP. If you want to find PHP script request source, is it from cli(command line) cron job or from browser? php_sapi_name is best function for you.

Now you know which function need to use for detect PHP excution source, and i.e., php_sapi_name.

Requirement:
How to detect PHP execution is from cli command line?

detect PHP execution is from cli command line

Solution:
php_sapi_name: Returns the type of interface between web server and PHP.

Returns a lowercase string that describes the type of interface (the Server API, SAPI) that PHP is using. For example, in CLI PHP this string will be “cli” whereas with Apache it may have several different values depending on the exact SAPI used.

php_sapi_name Usage example:


php_sapi_name();
if (php_sapi_name() == 'cli') {
    echo "You are using CLI PHP";
} else {
    echo "You are not using CLI PHP";
}

NOTE: As above mentioned whereas with Apache it may have several different values depending on the exact SAPI used. It means in some cases you may not get exact value what you expect i.e., cli.

Here suggestion is check php_sapi_name return value before use in condition, if it perfect for your requirement, use it safely, otherwise debug more and find another best solution.