In PHP how can I detect code is being run from command line

command-line-interface

When I run my PHP script from the command line I get the following notices. I assume the reason is that these variables such SERVER_NAME are not applicable when running without a browser.

In my code how can I detect that it is run from command line and skip those lines, so I dont have to see these notices?

I dont want to block these notices by piping to /dev/null, I would rather enhance the PHP code.

david@ubuntu:/var/www/user$ php cron_email.php
PHP Deprecated:  Comments starting with '#' are deprecated in /etc/php5/cli/conf.d/mcrypt.ini on line 1 in Unknown on line 0
PHP Notice:  Undefined index: SERVER_NAME in /var/www/user/codestart.php on line 14
PHP Notice:  Undefined index: REMOTE_ADDR in /var/www/user/codestart.php on line 97
PHP Notice:  Undefined index: REQUEST_URI in /var/www/user/codestart.php on line 99
PHP Notice:  Undefined index: HTTP_REFERER in /var/www/user/codestart.php on line 100
PHP Notice:  Undefined index: REQUEST_METHOD in /var/www/user/codestart.php on line 101
PHP Notice:  Undefined index: HTTP_USER_AGENT in /var/www/user/codestart.php on line 102

Best Answer

Check php_sapi_name(). If it =='cli', then you are calling from the command line.

http://php.net/manual/en/function.php-sapi-name.php