在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() 時要確保對輸入進行適當的轉義,以防止潛在的安全風險。