How to check if a shell command exists from PHP
I need something like this in 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');
}
Are there any solutions?
On Linux/Mac OS Try this:
function command_exist($cmd) {
$return = shell_exec(sprintf("which %s", escapeshellarg($cmd)));
return !empty($return);
}
Then use it in code:
if (!command_exist('makemiracle')) {
print 'no miracles';
} else {
shell_exec('makemiracle');
}
Update: As suggested by @camilo-martin you could simply use:
if (`which makemiracle`) {
shell_exec('makemiracle');
}
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;
}
你可以使用is_executable来检查它是否可执行,但你需要知道命令的路径,你可以使用which
命令来获取它。
上一篇: 我如何快速检查Linux是否使用Perl安装了unzip?
下一篇: 如何检查PHP是否存在shell命令