如果脚本是从控制台或浏览器请求运行,如何检查 PHP?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1042501/
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
How to check with PHP if the script is being run from the console or browser request?
提问by EdanB
I tried things like $_ENV['CLIENTNAME'] == 'Console' but that seems to work on only certain OS's (worked in windows, not linux).
我尝试了诸如 $_ENV['CLIENTNAME'] == 'Console' 之类的东西,但这似乎只适用于某些操作系统(适用于 Windows,不适用于 linux)。
I tried !empty($_ENV['SHELL']) but that doesn't work always either...
我试过 !empty($_ENV['SHELL']) 但这并不总是有效......
Is there a way to check this that will work in all OS's/environments?
有没有办法检查这个适用于所有操作系统/环境?
回答by Tom Haigh
Use php_sapi_name()
Returns a lowercase string that describes the type of interface (the Server API, SAPI) that PHP is using. For example, in CLI PHP this string will be "cli" whereas with Apache it may have several different values depending on the exact SAPI used.
返回描述 PHP 使用的接口类型(服务器 API,SAPI)的小写字符串。例如,在 CLI PHP 中,这个字符串将是“cli”,而在 Apache 中,它可能有几个不同的值,具体取决于所使用的确切 SAPI。
For example:
例如:
$isCLI = ( php_sapi_name() == 'cli' );
You can also use the constant PHP_SAPI
您还可以使用常量 PHP_SAPI
回答by Ganesh Kandu
Check on http://php.net/manual/en/features.commandline.php#105568"PHP_SAPI" Constant
检查http://php.net/manual/en/features.commandline.php#105568"PHP_SAPI" 常量
<?php
if (PHP_SAPI === 'cli')
{
// ...
}
?>
回答by Andrea Mauro
if ($argc > 0) {
// Command line was used
} else {
// Browser was used
}
$argc coounts the amount of arguments passed to the command line. Simply using php page.php, $argc will return 1
$argc 计算传递给命令行的参数数量。简单地使用 php page.php,$argc 将返回 1
Calling page.php with a browser, $argc will return NULL
用浏览器调用 page.php,$argc 会返回 NULL
回答by SteveK
I know this is an old question, but for the record, I see HTTP requests coming in without a User-Agent header and PHP does not automatically define HTTP_USER_AGENT in this case.
我知道这是一个老问题,但作为记录,我看到 HTTP 请求没有 User-Agent 标头,并且 PHP 在这种情况下不会自动定义 HTTP_USER_AGENT。
回答by Erel Segal-Halevi
One solution is to check whether STDIN is defined:
一种解决方案是检查是否定义了 STDIN:
if (!defined("STDIN")) {
die("Please run me from the console - not from a web-browser!");
}
回答by J-16 SDiZ
Check the HTTP_USER_AGENT , it should exist in http request
检查 HTTP_USER_AGENT ,它应该存在于 http 请求中

