使用exec和shell_exec函数执行命令时,不是所有的命令都适用。特别是,一些需要交互式输入或依赖终端功能的命令可能无法正常执行。下面是一些解决方法:
$output = `ls -l`;
echo $output;
// 或者
$output = system('ls -l', $return_val);
echo $output;
passthru('ls -l');
$descriptors = [
0 => ['pipe', 'r'], // 标准输入
1 => ['pipe', 'w'], // 标准输出
2 => ['pipe', 'w'], // 标准错误输出
];
$process = proc_open('ls -l', $descriptors, $pipes);
if (is_resource($process)) {
// 读取命令的输出
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
// 关闭进程
proc_close($process);
}
$script = <<
请注意,在使用exec和shell_exec函数执行命令时,要谨慎处理用户输入,以防止命令注入攻击。最好根据需要使用适当的过滤和验证来确保安全执行命令。