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
link|improve this question

feedback

2 Answers

up vote 7 down vote accepted

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

link|improve this answer
feedback

You could check for $_SERVER["SHELL"] or $_SERVER["TERM"]. They should exist for the cli but not when served by your webserver.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.