PHP - 如何最好地确定当前调用是来自 CLI 还是 Web 服务器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/933367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:23:05  来源:igfitidea点击:

PHP - how to best determine if the current invocation is from CLI or web server?

php

提问by Shameem

I need to determine whether the current invocation of PHP is from the command line (CLI) or from the web server (in my case, Apache with mod_php).

我需要确定当前对 PHP 的调用是来自命令行 (CLI) 还是来自 Web 服务器(在我的例子中是带有 mod_php 的 Apache)。

Any recommended methods?

有什么推荐的方法吗?

回答by Jordan S. Jones

php_sapi_nameis the function you will want to use as it returns a lowercase string of the interface type. In addition, there is the PHP constant PHP_SAPI.

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

Documentation can be found here: http://php.net/php_sapi_name

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

For example, to determine if PHP is being run from the CLI, you could use this function:

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

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

回答by Silver Moon

I have been using this function for a few years

我已经使用这个功能几年了

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;
}

回答by krowe2

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_sapi_name()确实不是执行此检查的最佳方法,因为它取决于检查许多可能的值。php-cgi 二进制文件可以从命令行、shell 脚本或作为 cron 作业调用,并且(在大多数情况下)它们也应该被视为“cli”,但php_sapi_name()将为它们返回不同的值(请注意,这不是“与普通版本的 PHP 一样,但您希望您的代码可以在任何地方工作,对吗?)。更不用说明年可能会有我们现在不可能知道的使用 PHP 的新方法。当我只关心天气时,我宁愿不考虑它我是否应该将我的输出包装在 HTML 中。

Fortunately, PHP has a way to check for this specifically. Just use http_response_code()without any parameters and it'll return TRUE if ran from a web server type environment and FALSE if ran from a CLI type environment. Here is the code:

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

$is_web=http_response_code()!==FALSE;

This will even work if you accidentally(?) set a response code from a script running from the CLI (or something like the CLI) before you call this.

如果您不小心(?)在调用之前从 CLI(或类似 CLI)运行的脚本中设置了响应代码,这甚至会起作用。

回答by Marc Towler

I think he means if PHP CLI is being invoked or if it is a response from a web request. The best way would be to use php_sapi_name()which if it was running a web request would echo Apache if that is what it was running.

我认为他的意思是 PHP CLI 是否正在被调用,或者它是否是来自 Web 请求的响应。最好的方法是使用php_sapi_name()which 如果它正在运行 Web 请求,则它会回显 Apache(如果它正在运行)。

To list of a few taken from the php docs on php_sapi_name():

列出一些取自 php文档的内容php_sapi_name()

  • aolserver
  • apache
  • apache2filter
  • apache2handler
  • caudium
  • cgi (until PHP 5.3)
  • cgi-fcgi
  • cli
  • cli-server (Built-in web serveras of PHP 5.4)
  • continuity
  • embed
  • fpm-fcgi
  • isapi
  • litespeed
  • milter
  • nsapi
  • phttpd
  • pi3web
  • roxen
  • thttpd
  • tux
  • webjames
  • 在线服务器
  • 阿帕奇
  • apache2filter
  • apache2handler
  • cgi(直到 PHP 5.3)
  • cgi-fcgi
  • 命令行
  • cli-server(自 PHP 5.4 起内置网络服务器
  • 连续性
  • 嵌入
  • fpm-fcgi
  • 伊萨皮
  • 极速
  • 米尔特
  • nsapi
  • phttpd
  • pi3web
  • 罗森
  • thttpd
  • 无尾礼服
  • 网络詹姆斯

回答by rbawaskar

This should handle all the cases (including php-cgi)

这应该处理所有情况(包括 php-cgi)

return (php_sapi_name() === 'cli' OR defined('STDIN'));

回答by Terry Lin

function is_cli() {
    return !http_response_code();
}

example:

例子:

if (is_cli()) {
    echo 'command line';
} else {
    echo 'browser';
}

回答by Ranjan

I used this:

我用过这个:

php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)

This is from Drush codebase, environment.inc where they have similar check to make.

这是来自 Drush 代码库,environment.inc,他们在那里进行了类似的检查。

回答by gnud

Try

尝试

isset($_SERVER['REQUEST_METHOD'])

if it's set, you're in a browser.

如果已设置,则您在浏览器中。

Alternatlely, you could check if

或者,您可以检查是否

isset($_SERVER['argv'])

but that might not be true on windows CLI, IDK.

但在 Windows CLI、IDK 上可能并非如此。

回答by Jonathan Fingland

According to http://jp2.php.net/manual/en/features.commandline.phpThere are a number of constants set only when running from the CLI. These constants are STDIN, STDOUT and STDERR. Testing for one of those will tell you if it is in cli mode

根据http://jp2.php.net/manual/en/features.commandline.php有许多常量仅在从 CLI 运行时设置。这些常量是 STDIN、STDOUT 和 STDERR。测试其中之一会告诉您它是否处于 cli 模式

回答by Sander

joomla way

joomla方式

if (array_key_exists('REQUEST_METHOD', $_SERVER)) die();