前言
PHP 執行系統指令有多種函式,各有特性與適用場景。本文詳細比較 `system()`、`exec()`、`passthru()`、`shell_exec()`、`proc_open()` 的差異、安全性與最佳實務。
四大核心函式比較
| 函式 | 回傳值 | 輸出處理 | 適用場景 | 安全風險 |
system() | 最後一行輸出 | 直接輸出到瀏覽器 | 簡單指令、即時顯示結果 | 高 |
exec() | 最後一行輸出 | 可選陣列接收所有行 | 需捕獲輸出供程式處理 | 高 |
passthru() | 狀態碼 | 直接輸出二進位資料 | 圖片/PDF/二進位輸出 | 高 |
shell_exec() | 完整輸出字串 | 回傳完整字串 | 需完整輸出字串處理 | 高 |
proc_open() | 資源控制代碼 | 雙向管道、完全控制 | 複雜互動、長時間程序 | 中(可控制輸入) |
詳細用法與範例
1. system() - 直接輸出
<?php
// 執行並直接輸出到瀏覽器
$lastLine = system('ls -la', $returnVar);
echo "返回碼: $returnVar\n";
echo "最後一行: $lastLine\n";
// ⚠️ 會直接輸出到標準輸出,難以捕獲
?>
2. exec() - 捕獲輸出陣列
<?php
$output = [];
$returnVar = 0;
// 執行指令,輸出每行存入 $output 陣列
$lastLine = exec('ls -la', $output, $returnVar);
echo "返回碼: $returnVar\n";
echo "最後一行: $lastLine\n";
echo "完整輸出:\n";
print_r($output);
// 實用:取得 Git 版本資訊
$version = exec('git describe --tags --always 2>/dev/null', $out, $code);
if ($code === 0) {
echo "Git 版本: $version";
}
?>
3. passthru() - 二進位輸出
<?php
// 輸出圖片/PDF 等二進位內容
header('Content-Type: image/png');
passthru('/usr/bin/convert -size 200x200 xc:blue png:-'); // ImageMagick 產生圖片
// 或執行產生二進位輸出的指令
passthru('cat /path/to/image.png');
?>
4. shell_exec() - 完整字串(反引號別名)
<?php
// 以下兩者等價
$output = shell_exec('ls -la');
$output = `ls -la`; // 反引號語法
echo $output; // 含換行的完整字串
// 實用:取得系統資訊
$cpuInfo = shell_exec('cat /proc/cpuinfo | grep "model name" | head -1');
echo $cpuInfo;
?>
5. proc_open() - 完全控制(進階)
<?php
$descriptors = [
0 => ['pipe', 'r'], // stdin
1 => ['pipe', 'w'], // stdout
2 => ['pipe', 'w'], // stderr
];
$process = proc_open('php -r "echo fgets(STDIN);"', $descriptors, $pipes);
if (is_resource($process)) {
// 寫入輸入
fwrite($pipes[0], "Hello from PHP!\n");
fclose($pipes[0]);
// 讀取輸出
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);
$returnCode = proc_close($process);
echo "STDOUT: $stdout";
echo "STDERR: $stderr";
echo "Exit code: $returnCode";
}
?>
安全性:絕對要做的事
1. 逃逸使用者輸入
<?php
$userInput = $_GET['filename'] ?? '';
// ❌ 極度危險:命令注入
// exec("ls $userInput");
// ✅ 正確:escapeshellarg() 包裹單一參數
$safeArg = escapeshellarg($userInput);
exec("ls $safeArg", $output);
// ✅ 正確:escapeshellcmd() 整個指令字串(較少用)
$safeCmd = escapeshellcmd("ls -la $userInput");
exec($safeCmd, $output);
?>
2. 避免 Shell 注入的最佳做法
<?php
// 最高安全性:不經由 Shell,直接執行程式
$process = proc_open(
['/usr/bin/ls', '-la', $userInput], // 陣列形式:程式 + 參數,不經 Shell
$descriptors,
$pipes
);
// 或使用 Symfony Process 元件(推薦現代專案)
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
$process = new Process(['ls', '-la', $userInput]);
$process->run();
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
echo $process->getOutput();
?>
常見實用範例
非同步背景執行
<?php
// 背景執行長時間任務
function runInBackground(string $command): void {
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
// Windows
$cmd = "start /B " . $command . " > NUL 2>&1";
pclose(popen($cmd, 'r'));
} else {
// Linux/Unix
$cmd = $command . " > /dev/null 2>&1 &";
exec($cmd);
}
}
// 使用
runInBackground('php /path/to/long_task.php arg1 arg2');
?>
取得程式 PID 並監控
<?php
$pid = null;
$descriptors = [1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
$proc = proc_open('sleep 100', $descriptors, $pipes);
$pid = (int)shell_exec("ps -o pid= --ppid {$proc}"); // 取得子進程 PID
// 稍後檢查是否還在運行
function isProcessRunning(int $pid): bool {
$result = shell_exec("ps -p $pid --no-headers");
return !empty(trim($result));
}
?>
超時控制
<?php
function execWithTimeout(string $command, int $timeoutSeconds): array {
$start = time();
$descriptors = [1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
$proc = proc_open($command, $descriptors, $pipes);
if (!is_resource($proc)) {
return ['output' => '', 'error' => '啟動失敗', 'code' => -1, 'timeout' => false];
}
// 非阻塞讀取
stream_set_blocking($pipes[1], false);
stream_set_blocking($pipes[2], false);
$output = '';
$error = '';
while (true) {
$status = proc_get_status($proc);
if (!$status['running']) break;
if (time() - $start >= $timeoutSeconds) {
proc_terminate($proc, SIGKILL);
return [
'output' => $output,
'error' => $error,
'code' => -1,
'timeout' => true
];
}
$output .= stream_get_contents($pipes[1]);
$error .= stream_get_contents($pipes[2]);
usleep(10000); // 10ms
}
$output .= stream_get_contents($pipes[1]);
$error .= stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$code = proc_close($proc);
return ['output' => $output, 'error' => $error, 'code' => $code, 'timeout' => false];
}
?>
Windows vs Linux 差異
| 差異點 | Linux/Unix | Windows |
| 路徑分隔符 | / | \ |
| 指令分隔 | ; 或 && | & |
| 背景執行 | & 結尾 | start /B |
| 空裝置 | /dev/null | NUL |
| 環境變數 | $VAR | %VAR% |
最佳實務總結
- 能用 PHP 內建函式就不要呼叫外部指令(如檔案操作用 `glob()`、`scandir()`、`file_get_contents()`)
- 必須呼叫外部程式時,優先用 `proc_open()` 陣列模式避免 Shell
- 所有使用者輸入經 `escapeshellarg()` 處理
- 限制執行權限:`open_basedir`、`disable_functions` 設定
- 記錄稽核日誌:記錄執行指令、參數、使用者、時間
- 設定超時與資源限制:防止失控進程耗盡資源