我在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)
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)
小智 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)