如何检查PHP脚本是否由shell运行

pau*_*ani 4 php

可能重复:
在php中,如何检测执行是从CLI模式还是通过浏览器?

如何通过Shell(命令行)或服务器检查PHP脚本是否正在运行?

MrC*_*ode 9

使用php_sapi_name功能:

if(php_sapi_name() == 'cli')
{
    // running from CLI
}
Run Code Online (Sandbox Code Playgroud)

从手册:

返回一个小写字符串,描述PHP正在使用的接口类型(Server API,SAPI).例如,在CLI PHP中,此字符串将为"cli",而对于Apache,它可能具有多个不同的值,具体取决于所使用的确切SAPI.可能的值列在下面.


gbt*_*mon 5

如果您真的对此感兴趣,请参阅shell解决方案:

ps -ef | grep $scriptname | grep -v grep;
if [[ $? -eq 0 ]]; then
    echo "PROCESS IS RUNNING";
fi
Run Code Online (Sandbox Code Playgroud)

Explination:

ps -ef            ## lists all running processes
grep $scriptname  ## keep only the process with the name we suppply
grep -v grep      ## the previous grep will show up in the ps -ef so this prevents false positives.  

if [[ $? -eq 0 ]]; then
    echo "PROCESS IS RUNNING";
fi                    ## if the last line returns something then process is running.  
Run Code Online (Sandbox Code Playgroud)