常用函數對比
| 函數 | 返回值 | 輸出處理 | 適用場景 |
| system() | 最後一行輸出 | 直接輸出到瀏覽器 | 簡單命令、需即時顯示 |
| passthru() | void | 二進制直接輸出 | 圖片/PDF 等二進制流 |
| exec() | 最後一行 | 將每行存入陣列參數 | 需捕獲完整輸出 |
| shell_exec() | 完整輸出字串 | 內部緩衝返回 | 需完整字串處理 |
| popen() | 資源控制代碼 | 串流讀寫 | 長時間運行、雙向通訊 |
| proc_open() | 資源陣列 | 完整管道控制 | 複雜進程控制、非阻塞 |
通用執行封裝函數
<?php
/**
* 安全執行系統命令並返回完整輸出
* @param string $cmd 命令字串
* @param int $timeout 超時秒數
* @return string|false 輸出內容或失敗 false
*/
function safeExec(string $cmd, int $timeout = 30)
{
// 禁用危險函數檢查
$disabled = explode(',', ini_get('disable_functions'));
$disabled = array_map('trim', $disabled);
$descriptors = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$proc = @proc_open($cmd, $descriptors, $pipes, null, null, ['suppress_errors' => true]);
if (!is_resource($proc)) {
// 降級嘗試
if (!in_array('shell_exec', $disabled)) return @shell_exec($cmd);
if (!in_array('exec', $disabled)) { @exec($cmd, $out); return implode("\n", $out); }
if (!in_array('system', $disabled)) { ob_start(); @system($cmd); return ob_get_clean(); }
return false;
}
// 非阻塞讀取,支援超時
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
$start = time();
$output = $error = '';
while (true) {
$status = proc_get_status($proc);
if (!$status['running']) break;
if (time() - $start > $timeout) {
proc_terminate($proc);
return false;
}
$output .= fread($pipes[1], 8192);
$error .= fread($pipes[2], 8192);
usleep(50000);
}
// 讀取剩餘
$output .= stream_get_contents($pipes[1]);
$error .= stream_get_contents($pipes[2]);
foreach ($pipes as $p) fclose($p);
proc_close($proc);
return $output ?: $error;
}
?>
安全最佳實踐
- 絕不直接拼接用戶輸入,使用 `escapeshellarg()`、`escapeshellcmd()`。
- 在 `php.ini` 中 `disable_functions = exec,shell_exec,system,passthru,popen,proc_open` 限制攻擊面。
- 使用 `proc_open` 替代舊函數,獲得更精細的控制與錯誤流分離。
- 記錄所有命令執行日誌,包含參數、執行時間、退出碼。