可能重複:
In php, how to detect the execution is from CLI mode or through browser?如何檢查是否PHP腳本由shell中運行
我如何檢查是否一個PHP腳本由殼牌(命令行)運行,或由服務器?
可能重複:
In php, how to detect the execution is from CLI mode or through browser?如何檢查是否PHP腳本由shell中運行
我如何檢查是否一個PHP腳本由殼牌(命令行)運行,或由服務器?
使用php_sapi_name
功能:
if(php_sapi_name() == 'cli')
{
// running from CLI
}
從Manual:
返回描述一個小寫的字符串,是PHP使用的接口類型(Server API,SAPI)。例如,在CLI中,這個字符串將是「cli」,而對於Apache,它可能有幾個不同的值,具體取決於使用的確切SAPI。下面列出了可能的值。
您可以檢查是否存在變量。
或者
您可以檢查這些:
if(isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'],"CLI") !== FALSE) {
///
}
繼承人,如果你是在真正感興趣的一個殼溶液:
ps -ef | grep $scriptname | grep -v grep;
if [[ $? -eq 0 ]]; then
echo "PROCESS IS RUNNING";
fi
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.
這部作品在我的產品環境:
if(substr(php_sapi_name(), 0, 3) == 'cli') {
die("You Should Use CGI To Run This Program.\n");
}
'substr'真的有必要嗎? –
還要看機器,安裝等... – Neal
我正在檢查一些索引um'$ _SERVER',但是n確定最好的方法是什麼。 – paulodiovani
我正在使用'preg_match('/^HTTP。* $/i',$ _SERVER ['SERVER_PROTOCOL'])'來查看它是否由http服務器運行,但我不想僅僅考慮其他因素由殼。 – paulodiovani