Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
share|improve this question
up vote 11 down vote accepted

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

share|improve this answer

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

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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