PHP - How to know if server allows shell_exec

旧巷老猫 提交于 2019-12-17 16:47:11

问题


On some servers, PHP is not allowed to run shell commands via shell_exec. How can I detect if current server allows running shell commands via PHP or not? How can I enable shell commands execution via PHP?


回答1:


First check that it's callable and then that it's not disabled:

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

This general approach works for any built in function, so you can genericize it:

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

Note to use stripos, because PHP function names are case insensitive.




回答2:


You may check the availablility of the function itself:

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

By the way: Is there a special requirement to use ''shell_exec'' rather than ''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.

EDIT #1

As DanFromGermany pointed out, you probably check then if it is executable. Something like this would do it

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

EDIT #2

If the example above may produce warnings you might do it in a more appropriate way. Just see this SO answer.



来源:https://stackoverflow.com/questions/21581560/php-how-to-know-if-server-allows-shell-exec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!