16

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?

arxoft
  • 1,385
  • 3
  • 17
  • 34

2 Answers2

21

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.

bishop
  • 37,830
  • 11
  • 104
  • 139
  • And you probably should check if safe-mod is enabled as well. – Christopher Will Feb 05 '14 at 15:56
  • 1
    @ChristopherWill:[Safe mode is deprecated in 5.3 and throws a fatal in 5.4](http://php.net/manual/en/features.safe-mode.php), so I didn't include it. Am I missing something by not including it (except obviously for <= 5.2, but that's EOL)? – bishop Feb 05 '14 at 17:37
  • 1
    Ah, I even did not know that's is deprecated. Thanks for the update. I guess that's it. – Christopher Will Feb 05 '14 at 19:46
6

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.

Community
  • 1
  • 1
Christopher Will
  • 2,991
  • 3
  • 29
  • 46