我需要确定当前对PHP的调用是来自命令行(CLI)还是来自web服务器(在我的情况下,使用mod_php的Apache)。

有什么推荐方法吗?


当前回答

我建议检查是否设置了$_SERVER数组的一些条目。

例如:

if (isset($_SERVER['REQUEST_METHOD'])) {
        print "HTTP request\n";
} else {
        print "CLI invocation\n";
}

其他回答

php_sapi_name() is really not the best way to perform this check because it depends on checking against many possible values. The php-cgi binary can be called from the command line, from a shell script or as a cron job and (in most cases) these should also be treated as 'cli' but php_sapi_name() will return different values for these (note that this isn't the case with the plain version of PHP but you want your code to work anywhere, right?). Not to mention that next year there may be new ways to use PHP that we can't possibly know now. I'd rather not think about it when all I care about is weather I should wrap my output in HTML or not.

幸运的是,PHP有一种方法可以检查这一点。只需使用http_response_code(),不带任何参数,如果从web服务器类型环境运行,它将返回TRUE,如果从CLI类型环境运行,则返回FALSE。代码如下:

$is_web=http_response_code()!==FALSE;

即使您在调用之前不小心(?)从从CLI(或类似CLI的东西)运行的脚本设置了响应代码,这也可以工作。

我已经使用这个函数好几年了

function is_cli()
{
    if ( defined('STDIN') )
    {
        return true;
    }

    if ( php_sapi_name() === 'cli' )
    {
        return true;
    }

    if ( array_key_exists('SHELL', $_ENV) ) {
        return true;
    }

    if ( empty($_SERVER['REMOTE_ADDR']) and !isset($_SERVER['HTTP_USER_AGENT']) and count($_SERVER['argv']) > 0) 
    {
        return true;
    } 

    if ( !array_key_exists('REQUEST_METHOD', $_SERVER) )
    {
        return true;
    }

    return false;
}

我试一试:

echo exec('whoami');

通常网络服务器在不同的用户名下运行,所以这应该是说明问题的。

我建议检查是否设置了$_SERVER数组的一些条目。

例如:

if (isset($_SERVER['REQUEST_METHOD'])) {
        print "HTTP request\n";
} else {
        print "CLI invocation\n";
}

Php_sapi_name是您希望使用的函数,因为它返回接口类型的小写字符串。此外,还有一个PHP常量PHP_SAPI。

文档可以在这里找到:http://php.net/php_sapi_name

例如,要确定PHP是否正在从CLI运行,你可以使用这个函数:

function isCommandLineInterface()
{
    return (php_sapi_name() === 'cli');
}