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?

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top