在PHP中,我如何检测正在从命令行运行的代码?

当我从命令行运行我的PHP脚本时,我收到以下通知。 我假设原因是这些SERVER_NAMEvariables在没有浏览器的情况下运行是不适用的。

在我的代码中,我怎么能检测到它是从命令行运行,并跳过这些行,所以我没有看到这些通知?

我不想阻塞这些通知pipe道到/ dev / null,我宁愿增强PHP代码。

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 

检查php_sapi_name() 。 如果它=='cli' ,那么你是从命令行调用。

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

您可以检查$_SERVER["SHELL"]$_SERVER["TERM"] 。 他们应该存在的cli但不是由您的networking服务器提供。