如何使用PHP检查是否正在从控制台或浏览器请求中运行脚本? [英] How to check with PHP if the script is being run from the console or browser request?

查看:188
本文介绍了如何使用PHP检查是否正在从控制台或浏览器请求中运行脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了诸如$ _ENV ['CLIENTNAME'] =='Console'之类的操作,但这似乎仅适用于某些操作系统(适用于Windows,不适用于Linux)。

I tried things like $_ENV['CLIENTNAME'] == 'Console' but that seems to work on only certain OS's (worked in windows, not linux).

我尝试了!empty($ _ ENV ['SHELL']),但这也不总是可行的...

I tried !empty($_ENV['SHELL']) but that doesn't work always either...

有没有一种方法可以检查它在所有操作系统/环境中是否都能正常工作?

Is there a way to check this that will work in all OS's/environments?

推荐答案

使用 php_sapi_name()

返回一个小写的字符串,该字符串描述了PHP使用的接口类型(
服务器API,SAPI)。
例如,在CLI PHP中,此字符串
将为 cli,而对于Apache,
可能具有多个不同的值
,具体取决于所使用的SAPI。

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.

例如:

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

您还可以使用常量 PHP_SAPI

这篇关于如何使用PHP检查是否正在从控制台或浏览器请求中运行脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆