One method to know if the script being executed has been started through cli, apache or any other API is to use PHP_SAPI:
if (PHP_SAPI != 'cli') { ... }will ensure that the script is executed in a command-line context before doing what's inside the brackets.