2012-11-26 138 views
4

可能重複:
In php, how to detect the execution is from CLI mode or through browser?如何檢查是否PHP腳本由shell中運行

我如何檢查是否一個PHP腳本由殼牌(命令行)運行,或由服務器?

+0

還要看機器,安裝等... – Neal

+0

我正在檢查一些索引um'$ _SERVER',但是n確定最好的方法是什麼。 – paulodiovani

+0

我正在使用'preg_match('/^HTTP。* $/i',$ _SERVER ['SERVER_PROTOCOL'])'來查看它是否由http服務器運行,但我不想僅僅考慮其他因素由殼。 – paulodiovani

回答

9

使用php_sapi_name功能:

if(php_sapi_name() == 'cli') 
{ 
    // running from CLI 
} 

Manual

返回描述一個小寫的字符串,是PHP使用的接口類型(Server API,SAPI)。例如,在CLI中,這個字符串將是「cli」,而對於Apache,它可能有幾個不同的值,具體取決於使用的確切SAPI。下面列出了可能的值。

2

您可以檢查是否存在變量。

或者

您可以檢查這些:

if(isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'],"CLI") !== FALSE) { 
/// 
} 
5

繼承人,如果你是在真正感興趣的一個殼溶液:

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. 
+0

這是做什麼用的? –

+0

@BrendanLong增加了一步一步探索答案。 – gbtimmon

+0

我仍然對這個問題如何回答感到困惑。是否有任何機會發布錯誤的問題? –

0

這部作品在我的產品環境:

if(substr(php_sapi_name(), 0, 3) == 'cli') { 
    die("You Should Use CGI To Run This Program.\n"); 
} 
+0

'substr'真的有必要嗎? –

相關問題