在 PHP 中,如何检测是从 CLI 模式还是通过浏览器执行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1991346/
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 04:33:48  来源:igfitidea点击:

In PHP, how to detect the execution is from CLI mode or through browser ?

php

提问by binoy

I have a common script which Im including in my PHPcron files and the files which are accessing through the browser. Some part of the code, I need only for non cron files. How can I detect whether the execution is from CLI or through browser (I know it can be done by passing some arguments with the cron files but I dont have access to crontab). Is there any other way ?

我有一个通用脚本,它包含在我的 PHPcron 文件和通过浏览器访问的文件中。代码的某些部分,我只需要非 cron 文件。如何检测执行是来自 CLI 还是通过浏览器(我知道可以通过使用 cron 文件传递​​一些参数来完成,但我无法访问 crontab)。还有其他方法吗?

回答by Alexander V. Ilyin

Use the php_sapi_name()function.

使用该php_sapi_name()功能。

if (php_sapi_name() == "cli") {
    // In cli-mode
} else {
    // Not in cli-mode
}

Here are some relevant notes from the docs:

以下是文档中的一些相关注释:

php_sapi_name— Returns the type of interface between web server and PHP

Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, cli-server, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.

php_sapi_name— 返回 Web 服务器和 PHP 之间的接口类型

尽管并非详尽无遗,但可能的返回值包括 aolserver、apache、apache2filter、apache2handler、caudium、cgi(直到 PHP 5.3)、cgi-fcgi、cli、cli-server、continuous、embed、isapi、litespeed、milter、nsapi、phttpd、 pi3web、roxen、thttpd、tux 和 webjames。

回答by Linus Unneb?ck

if(php_sapi_name() == "cli") {
    //In cli-mode
} else {
    //Not in cli-mode
}

回答by just somebody

There is a constant PHP_SAPIhas the same value as php_sapi_name().

有一个常数与PHP_SAPI具有相同的值php_sapi_name()

(available in PHP >= 4.2.0)

(适用于 PHP >= 4.2.0)

回答by Jimmy Shelter

I think you can see it from the $_SERVER variables. Try to print out the $_SERVER array for both browser & CLI and you should see differences.

我认为您可以从 $_SERVER 变量中看到它。尝试为浏览器和 CLI 打印出 $_SERVER 数组,您应该会看到差异。

回答by Etienne Dechamps

You can use:

您可以使用:

if (isset($argc))
{
    // CLI
}
else
{
    // NOT CLI
}