PHP 執行系統指令是強大但高風險的功能。本文詳細說明 `shell_exec`、`exec`、`passthru`、`proc_open` 差異、輸出捕獲技巧、權限控管與資安加固原則。
| 函式 | 回傳值 | 輸出處理 | 適用場景 |
|---|---|---|---|
| shell_exec | 完整輸出字串 / false | 自動捕獲 stdout+stderr | 簡單指令、需完整輸出字串 |
| exec | 最後一行輸出;陣列參數可取得所有行 | 需傳陣列參數捕獲 | 需逐行處理、取得退出碼 |
| passthru | 退出碼 | 直接輸出到瀏覽器/標準輸出 | 二進位輸出 (圖片、PDF)、串流 |
| proc_open | 資源控制陣列 | 雙向管道、非阻塞、進程控制 | 複雜互動、長時間運行、需 stdin 傳入 |
預設僅捕獲 stdout。若指令寫入 stderr(錯誤、警告、進度),PHP 會收到空字串。解決:在指令末尾加上 2>&1 將 stderr 重導向 stdout。
<?php
// 正確:捕獲完整輸出 (stdout + stderr)
$output = shell_exec("sudo /usr/local/nginx/sbin/nginx -t 2>&1");
echo "執行結果:
" . nl2br(htmlspecialchars($output));
<?php
function runCommandWithTimeout($cmd, $timeout = 30, $stdin = '') {
$descriptors = [
0 => ['pipe', 'r'], // stdin
1 => ['pipe', 'w'], // stdout
2 => ['pipe', 'w'], // stderr
];
$proc = proc_open($cmd, $descriptors, $pipes);
if (!is_resource($proc)) throw new RuntimeException("proc_open 失敗: $cmd");
// 寫入 stdin
if ($stdin !== '') {
fwrite($pipes[0], $stdin);
}
fclose($pipes[0]);
// 非阻塞讀取
stream_set_blocking($pipes[1], false);
stream_set_blocking($pipes[2], false);
$stdout = ''; $stderr = '';
$start = time();
while (true) {
$read = [$pipes[1], $pipes[2]];
$write = null; $except = null;
if (stream_select($read, $write, $except, 0, 200000)) { // 0.2 秒
foreach ($read as $pipe) {
$data = fread($pipe, 8192);
if ($pipe === $pipes[1]) $stdout .= $data;
else $stderr .= $data;
}
}
$status = proc_get_status($proc);
if (!$status['running']) break;
if (time() - $start > $timeout) {
proc_terminate($proc, SIGKILL);
throw new RuntimeException("指令超時: $cmd");
}
usleep(50000);
}
fclose($pipes[1]); fclose($pipes[2]);
$returnCode = proc_close($proc);
return ['stdout' => $stdout, 'stderr' => $stderr, 'code' => $returnCode];
}
// 使用
try {
$result = runCommandWithTimeout('php -r "sleep(5); echo \"done\";"', 3);
} catch (RuntimeException $e) {
echo $e->getMessage(); // 指令超時
}
$ip = escapeshellarg($_GET['ip']); // 單一參數加單引號並跳脫
$output = shell_exec("ping -c 3 $ip");
| 場景 | 推薦函式 | 關鍵點 |
|---|---|---|
| 健康檢查/狀態查詢 | shell_exec | 2>&1 捕獲 stderr、逾時控制 |
| 影像處理 | proc_open | 串流處理大檔、非阻塞、進度回報 |
| 批次匯入/ETL | proc_open + 背景程序 | nohup/setsid 脫離終端、PID 檔管理 |
| 系統管理操作 | sudo + 白名單 | sudoers 僅允許特定指令、參數驗證 |
「能用 PHP 原生函式/擴充庫解決,就不要呼叫 Shell」。必須呼叫時,嚴守「輸入白名單、參數跳脫、最小權限、輸出捕獲」四大鐵律。