什么是确定命令行与PHP脚本的http执行的规范方法? [英] What is the canonical way to determine commandline vs. http execution of a PHP script?

查看:172
本文介绍了什么是确定命令行与PHP脚本的http执行的规范方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP脚本,需要确定是否已通过命令行或通过HTTP执行,主要用于输出格式化目的。这是什么规范的方式?我认为这是检查 SERVER ['argc'] ,但事实证明,这是填充,即使使用'Apache 2.0处理程序'服务器API。

I have a PHP script that needs to determine if it's been executed via the command-line or via HTTP, primarily for output-formatting purposes. What's the canonical way of doing this? I had thought it was to inspect SERVER['argc'], but it turns out this is populated, even when using the 'Apache 2.0 Handler' server API.

推荐答案

使用 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 - 返回Web服务器和PHP之间的接口类型

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

虽然不完全,但可能的返回值包括aolserver,apache ,apache2filter,apache2handler,caudium,cgi(直到PHP 5.3),cgi-fcgi,cli,cli-server,continuity,embed,isapi,litespeed,milter,nsapi,phttpd,pi3web,roxen,thttpd,tux和webjames。 / p>

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> = 4.2.0中,还有一个预定义的常量, PHP_SAPI ,其值与 php_sapi_name()相同。

In PHP >= 4.2.0, there is also a predefined constant, PHP_SAPI, that has the same value as php_sapi_name().

这篇关于什么是确定命令行与PHP脚本的http执行的规范方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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