2014-02-05 58 views
7

在某些服務器上,PHP不允許通過shell_exec運行shell命令。如何檢測當前服務器是否允許通過PHP運行shell命令?我如何通過PHP啓用shell命令執行?PHP - 如何知道服務器是否允許shell_exec

+0

'我如何通過PHP啓用shell命令執行?'只在根配置中。這是一項安全功能。 –

+2

'<?php echo ini_get('disable_functions'); ?>' – DanFromGermany

回答

9

首先檢查它的調用,然後它沒有禁用:

is_callable('shell_exec') && false === stripos(ini_get('disable_functions'), 'shell_exec'); 

這種一般方法適用於任何內置的功能,這樣你就可以泛化它:

function isEnabled($func) { 
    return is_callable($func) && false === stripos(ini_get('disable_functions'), $func); 
} 
if (isEnabled('shell_exec')) { 
    shell_exec('echo "hello world"'); 
} 

注意使用stripos ,因爲PHP函數名稱不區分大小寫。

+0

你可能應該檢查是否啓用了安全模式。 –

+1

@ChristopherWill:[安全模式在5.3中被棄用,並在5.4中引發致命錯誤](http://php.net/manual/en/features.safe-mode.php),所以我沒有包含它。我錯過了什麼,不包括它(除非明顯是<= 5.2,但這是EOL)? – bishop

+1

啊,我什至不知道這是不推薦。感謝更新。我想就是這樣。 –

2

您可以檢查函數本身的可用性等:

if(function_exists('shell_exec')) { 
    echo "exec is enabled"; 
} 

順便說一句:有沒有辦法使用'了shell_exec',而不是'exex'有特殊要求?

php.net

Note: 
This function can return NULL both when an error occurs or the program 
produces no output. It is not possible to detect execution failures using 
this function. exec() should be used when access to the program exit code 
is required. 

編輯#1

由於DanFromGermany指出的那樣,你可能檢查那麼如果它是可執行的。像這樣的東西會做

if(shell_exec('echo foobar') == 'foobar'){ 
    echo 'shell_exec works'; 
} 

編輯#2

如果上面的例子可以在一個更合適的方式產生,你可以做到這一點的警告。只需see this SO answer

+1

否。該功能已禁用,但確實存在。這不起作用。 – DanFromGermany

+0

-1'function_exists'不足以測試「啓用」並調用'shell_exec'來查看它是否「有效」似乎過度殺傷。 – bishop

+0

@bishop是的,你是完全正確的。這就是爲什麼我更新我的答案,並插入一個很好的答案的參考。 –

相關問題