本文介绍了在PHP中,如何检测是从CLI模式还是通过浏览器执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用脚本,Im包含在我的PHPcron文件中以及正在通过浏览器访问的文件中.代码的某些部分,我只需要非cron文件.如何检测执行是从CLI还是通过浏览器执行(我知道可以通过将某些参数与cron文件一起传递来完成,但我无权访问crontab).还有其他办法吗?

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 ?

推荐答案

使用 php_sapi_name() 函数. /p>

Use the php_sapi_name() function.

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

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

Here are some relevant notes from the docs:

尽管不详尽,但可能的返回值包括aolserver,apache,apache2filter,apache2handler,caudium,cgi(直到PHP 5.3),cgi-fcgi,cli,cli-server,连续性,嵌入,isapi,litespeed,milter,nsapi ,phttpd,pi3web,roxen,thttpd,tux和webjames.

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中,如何检测是从CLI模式还是通过浏览器执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:20