开发者

Check if "exec" is disabled [duplicate]

开发者 https://www.devze.com 2023-01-20 05:11 出处:网络
This question already has answers here: PHP exec - check if enabled or disabled (10 answers) Closed 9 years ago.
This question already has answers here: PHP exec - check if enabled or disabled (10 answers) Closed 9 years ago. 开发者_如何学C

Is there any function in PHP that I can use to detect whether or not the exec function is available?


<?php
function exec_enabled() {
  $disabled = explode(',', ini_get('disable_functions'));
  return !in_array('exec', $disabled);
}
?>

EDIT: Fixed the explode as per Ziagl's comment.


The following function is more robust. It deals with the disabled_functions value having 0 or more spaces between function names, checks the suhosin patch's blacklist setting, covers safe_mode, and stores the answer for future reference.

function is_exec_available() {
    static $available;

    if (!isset($available)) {
        $available = true;
        if (ini_get('safe_mode')) {
            $available = false;
        } else {
            $d = ini_get('disable_functions');
            $s = ini_get('suhosin.executor.func.blacklist');
            if ("$d$s") {
                $array = preg_split('/,\s*/', "$d,$s");
                if (in_array('exec', $array)) {
                    $available = false;
                }
            }
        }
    }

    return $available;
}


You can search the ini setting disable_functions for the exec() function.

if( false !== strpos(ini_get("disable_functions"), "exec") ) {
 // exec() is disabled

Just for completeness, note that PHP Safe Mode puts some restrictions on the function too.


You also need to check whether safe_mode is active as exec is unavailable if safe_mode is on

function is_exec_available() {

    // Are we in Safe Mode
    if ( $safe_mode = ini_get( 'safe_mode' ) && strtolower( $safe_mode ) != 'off' )
        return false;

    // Is shell_exec disabled?
    if ( in_array( 'exec', array_map( 'trim', explode( ',', ini_get( 'disable_functions' ) ) ) ) )
        return false;

    return true;

}


A one-line compilation of safe mode, function exists, and disabled exec using some of the techniques found on various SO posts.

This will check that exec is available and enabled BEFORE trying to run it. If you run exec() and the function does not exist or is disabled a warning will be generated. Depending on the server settings that may render to the browser and will almost-always write a line to a log file = performance hit.

// Exec function exists.
// Exec is not disabled.
// Safe Mode is not on.
$exec_enabled =
     function_exists('exec')                                            &&
     !in_array('exec', array_map('trim',explode(', ', ini_get('disable_functions'))))     &&
              !(strtolower( ini_get( 'safe_mode' ) ) != 'off')
     ;


if ($exec_enabled) { exec('blah'); }
0

精彩评论

暂无评论...
验证码 换一张
取 消