在PHP中,exec() 函数可以用于执行外部命令
proc_open() 函数:proc_open() 函数提供了一个更灵活的接口来执行外部命令并处理输入输出重定向。以下是一个示例:
<?php $command = 'your_command_here'; $input = 'input_data_here'; $output = 'output_data_here'; $error_output = 'error_output_data_here'; $process = proc_open($command, [ 0 => ['pipe', 'r'], // 标准输入,子进程从此管道中读取数据 1 => ['pipe', 'w'], // 标准输出,子进程向此管道中写入数据 2 => ['pipe', 'w'] // 标准错误,子进程向此管道中写入数据 ], $pipes); if (is_resource($process)) { fwrite($pipes[0], $input); // 将输入数据写入子进程 fclose($pipes[0]); // 关闭标准输入,不再发送数据 $stdout = stream_get_contents($pipes[1]); // 从子进程读取标准输出 fclose($pipes[1]); // 关闭标准输出 $stderr = stream_get_contents($pipes[2]); // 从子进程读取标准错误 fclose($pipes[2]); // 关闭标准错误 $return_value = proc_close($process); // 关闭子进程并获取返回值 echo "Standard Output:\n" . $stdout; echo "Standard Error:\n" . $stderr; echo "Return Value: " . $return_value; } else { echo "Failed to start the process."; } ?> shell_exec() 函数:shell_exec() 函数允许您执行一个命令并返回命令的输出。但是,它不支持直接处理输入输出重定向。如果您需要将输入传递给命令并将输出保存到文件,可以使用以下方法:
<?php $command = 'your_command_here'; $input = 'input_data_here'; $output_file = 'output_data_here'; // 将输入数据传递给命令 $command .= " < input_file.txt"; // 将标准输出重定向到文件 $command .= " > " . escapeshellarg($output_file); // 执行命令 exec($command); ?> 在这个示例中,我们将输入数据写入一个名为 input_file.txt 的文件,然后将标准输出重定向到我们希望保存输出的文件。请注意,使用 shell_exec() 时要确保对输入进行适当的转义,以防止潜在的安全风险。