In what scenarios should PHP scripts be executed as CLI instead of on a web server?

PHP scripts should be executed as CLI (Command Line Interface) instead of on a web server when the script needs to perform tasks that are not related to serving web pages, such as running scheduled tasks, batch processing, or interacting with the system directly. Running scripts as CLI allows for better control over the environment and execution, as well as providing access to additional features and libraries that may not be available in a web server context.

<?php
// CLI script example
if (php_sapi_name() !== 'cli') {
    die("This script can only be run from the command line.");
}

// Your PHP script logic here
echo "Hello, CLI!";