如何检查PHP中是否存在shell命令

mim*_*ock 33 php linux exec

我在php中需要这样的东西:

If (!command_exists('makemiracle')) {
  print 'no miracles';
  return FALSE;
}
else {
  // safely call the command knowing that it exists in the host system
  shell_exec('makemiracle');
}
Run Code Online (Sandbox Code Playgroud)

有什么解决方案吗?

doc*_*uke 46

在Linux/Mac OS上试试这个:

function command_exist($cmd) {
    $return = shell_exec(sprintf("which %s", escapeshellarg($cmd)));
    return !empty($return);
}
Run Code Online (Sandbox Code Playgroud)

然后在代码中使用它:

if (!command_exist('makemiracle')) {
    print 'no miracles';
} else {
    shell_exec('makemiracle');
}
Run Code Online (Sandbox Code Playgroud)

更新: 根据@ camilo-martin的建议你可以简单地使用:

if (`which makemiracle`) {
    shell_exec('makemiracle');
}
Run Code Online (Sandbox Code Playgroud)

  • @tjbp更短:`return !! \`哪个$ cmd \``.它实际上是如此之短,以至于我会在条件中使用它:`if(\`which foo \`){...}` (10认同)
  • [我不认为你应该使用`which`.(http://stackoverflow.com/a/677212/937377) (6认同)
  • 这可以简化为`return!empty(shell_exec("$ cmd"));` (4认同)
  • `"which%s"`如果找不到程序将导致STDERR上的输出,并将输出到屏幕(如果从CLI运行)或错误日志(如果从Web运行).使用`"which%s 2>/dev/null"`来抑制此输出. (3认同)
  • 也不是你可以在Windows上使用`where`. (2认同)

Der*_*son 13

Windows使用whereUNIX系统which来允许本地化命令.如果找不到命令,两者都将在STDOUT中返回一个空字符串.

对于PHP支持的每个Windows版本,PHP_OS目前都是WINNT.

这是一个便携式解决方案:

/**
 * Determines if a command exists on the current environment
 *
 * @param string $command The command to check
 * @return bool True if the command has been found ; otherwise, false.
 */
function command_exists ($command) {
  $whereIsCommand = (PHP_OS == 'WINNT') ? 'where' : 'which';

  $process = proc_open(
    "$whereIsCommand $command",
    array(
      0 => array("pipe", "r"), //STDIN
      1 => array("pipe", "w"), //STDOUT
      2 => array("pipe", "w"), //STDERR
    ),
    $pipes
  );
  if ($process !== false) {
    $stdout = stream_get_contents($pipes[1]);
    $stderr = stream_get_contents($pipes[2]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    proc_close($process);

    return $stdout != '';
  }

  return false;
}
Run Code Online (Sandbox Code Playgroud)

  • 对于Unix,不推荐使用它 - 请参阅http://stackoverflow.com/questions/592620/how-to-check-if-a-program-exists-from-a-bash-script (2认同)
  • 如果找不到命令,Windows并不总是返回空字符串.还有"INFO:无法找到给定模式的文件"这样的东西. (2认同)

小智 5

基于@jcubic和应该避免的“哪个”,这是我想到的跨平台:

function verifyCommand($command) :bool {
  $windows = strpos(PHP_OS, 'WIN') === 0;
  $test = $windows ? 'where' : 'command -v';
  return is_executable(trim(shell_exec("$test $command")));
}
Run Code Online (Sandbox Code Playgroud)