Determine PHP script Invocation: CLI or by the Web Server

In most cases you can distinguish if a PHP script was invoked from the command line (or Cron) or by the web server, using php_sapi_name().

php_sapi_name() will return cli on CLI (or Cron) invocation and some other values on invocation by Web Server (e.g. apache2handler for Apache).

Example

A simple example:

<?php
if(php_sapi_name() == 'cli') {
        // your code here
} else {
        // your code here
}
?>

References

From PHP manual