How to check if a shell command exists from PHP

后端 未结 7 1019
孤街浪徒
孤街浪徒 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条回答
  •  误落风尘
    2020-12-25 11:26

    Platform independent solution:

    function cmd_exists($command)
    {
        if (\strtolower(\substr(PHP_OS, 0, 3)) === 'win')
        {
            $fp = \popen("where $command", "r");
            $result = \fgets($fp, 255);
            $exists = ! \preg_match('#Could not find files#', $result);
            \pclose($fp);   
        }
        else # non-Windows
        {
            $fp = \popen("which $command", "r");
            $result = \fgets($fp, 255);
            $exists = ! empty($result);
            \pclose($fp);
        }
    
        return $exists;
    }
    

提交回复
热议问题