简体   繁体   English

如果从控制台或浏览器请求运行脚本,如何检查PHP?

[英]How to check with PHP if the script is being run from the console or browser request?

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... 我试过了!空($ _ ENV ['SHELL'])但是这总是不起作用......

Is there a way to check this that will work in all OS's/environments? 有没有办法检查这将适用于所有操作系统/环境?

Use php_sapi_name() 使用php_sapi_name()

Returns a lowercase string that describes the type of interface (the Server API, SAPI) that PHP is using. 返回一个小写字符串,描述PHP正在使用的接口类型(Server API,SAPI)。 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. 例如,在CLI PHP中,此字符串将为“cli”,而对于Apache,它可能具有多个不同的值,具体取决于所使用的确切SAPI。

For example: 例如:

$isCLI = ( php_sapi_name() == 'cli' );

You can also use the constant PHP_SAPI 您还可以使用常量PHP_SAPI

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')
{
   // ...
}
?> 

我知道这是一个老问题,但是为了记录,我看到没有User-Agent头的HTTP请求进入,在这种情况下PHP不会自动定义HTTP_USER_AGENT。

if ($argc > 0) {
    // Command line was used
} else {
    // Browser was used
}

$argc coounts the amount of arguments passed to the command line. $ argc计算传递给命令行的参数量。 Simply using php page.php, $argc will return 1 只需使用php page.php,$ argc将返回1

Calling page.php with a browser, $argc will return NULL 使用浏览器调用page.php,$ argc将返回NULL

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!");
}

检查HTTP_USER_AGENT,它应该存在于http请求中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM