萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 系統命令執行函數深度比較與通用封裝

常用函數對比

函數返回值輸出處理適用場景
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;
}
?>

安全最佳實踐

  1. 絕不直接拼接用戶輸入,使用 `escapeshellarg()`、`escapeshellcmd()`。
  2. 在 `php.ini` 中 `disable_functions = exec,shell_exec,system,passthru,popen,proc_open` 限制攻擊面。
  3. 使用 `proc_open` 替代舊函數,獲得更精細的控制與錯誤流分離。
  4. 記錄所有命令執行日誌,包含參數、執行時間、退出碼。
copyright © 萬盛學電腦網 all rights reserved