How to check if a shell command exists from PHP

后端 未结 7 1007
孤街浪徒
孤街浪徒 2020-12-25 11:07

I need something like this in php:

If (!command_exists(\'makemiracle\')) {
  print \'no miracles\';
  return FALSE;
}
else {
  // safely call the command kno         


        
7条回答
  •  梦毁少年i
    2020-12-25 11:41

    Windows uses where, UNIX systems which to allow to localize a command. Both will return an empty string in STDOUT if the command isn't found.

    PHP_OS is currently WINNT for every supported Windows version by PHP.

    So here a portable solution:

    /**
     * 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;
    }
    

提交回复
热议问题