The function php_sapi_name()
and the constant PHP_SAPI
both return the type of interface (Server API) that is being used by PHP. They can be used to restrict the execution of a script to the command line, by checking whether the output of the function is equal to cli
.
if (php_sapi_name() === 'cli') {
echo "Executed from command line\n";
} else {
echo "Executed from web browser\n";
}
The drupal_is_cli()
function is an example of a function that detects whether a script has been executed from the command line:
function drupal_is_cli() {
return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));
}