Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

2 Answers 2

up vote 9 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

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

 
discard

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.