并非所有命令都适用于exec/shell_exec函数。
创始人
2024-12-18 10:30:08
0

使用exec和shell_exec函数执行命令时,不是所有的命令都适用。特别是,一些需要交互式输入或依赖终端功能的命令可能无法正常执行。下面是一些解决方法:

  1. 使用反引号或shell_exec的替代函数:可以尝试使用反引号操作符(``)或system函数来执行命令,看看是否能够正常工作。这些函数也可以用于执行命令,并返回命令的输出。
$output = `ls -l`;
echo $output;

// 或者

$output = system('ls -l', $return_val);
echo $output;
  1. 使用passthru函数:如果你需要直接将命令的输出发送到浏览器,可以尝试使用passthru函数。它会将命令的输出直接发送到输出缓冲区,而不需要将其存储在变量中。
passthru('ls -l');
  1. 使用proc_open函数:如果需要更高级的控制,可以尝试使用proc_open函数。它允许你创建一个新进程,并与其进行交互。你可以使用proc_open函数来执行命令,并读取其输出。
$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);
}
  1. 将命令包装在一个脚本中:如果你需要执行的命令无法在exec或shell_exec函数中正常工作,可以尝试将命令包装在一个脚本中,然后使用exec或shell_exec函数来执行该脚本。
$script = <<