Comment vérifier si une commande shell existe depuis PHP

J’ai besoin de quelque chose comme ça dans 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'); } 

Y a-t-il des solutions?

Sous Linux / Mac OS Essayez ceci:

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

Ensuite, utilisez-le dans le code:

 if (!command_exist('makemiracle')) { print 'no miracles'; } else { shell_exec('makemiracle'); } 

Mise à jour: Comme suggéré par @ camilo-martin, vous pouvez simplement utiliser:

 if (`which makemiracle`) { shell_exec('makemiracle'); } 

Windows utilise where , les systèmes UNIX which permettent de localiser une commande. Les deux renverront une chaîne vide dans STDOUT si la commande est introuvable.

PHP_OS est actuellement WINNT pour chaque version de Windows supscope par PHP.

Alors voici une solution portable:

 /** * Determines if a command exists on the current environment * * @param ssortingng $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; } 

Vous pouvez utiliser is_executable pour vérifier s’il est exécutable, mais vous devez connaître le chemin de la commande, que vous pouvez utiliser avec which commande.

Solution indépendante de la plate-forme:

 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; } 
 function checkIfCommandExists($cmd){ $prefix = strpos(strtolower(PHP_OS),'win') > -1 ? 'where' : 'which'; exec("{$prefix} {$cmd}", $output, $returnVal); $returnVal !== 0 } 

celle-ci est une solution crossplatform utilisant la valeur de retour de “where” et “which” 🙂

Non il n’y en a pas.

Même en ayant un access direct à un shell, vous ne savez pas si une commande existe. Il y a quelques astuces comme wheris ou find / -name yourcommand mais cela ne garantit pas à 100% que vous pouvez exécuter la commande.