萬盛學電腦網

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

PHP 執行 Shell 命令中文亂碼終極解決:編碼轉換與輸出捕獲最佳實踐

亂碼根因

Shell 命令輸出編碼取決於終端機環境編碼(通常為系統 Locale),而 PHP 腳本內部編碼通常為 UTF-8。常見組合:

  • Linux 伺服器:LANG=zh_TW.UTF-8 或 zh_CN.UTF-8 → 輸出 UTF-8
  • Windows 伺服器:cp936 (GBK) / cp950 (Big5) → 輸出 ANSI
  • 舊系統/特定環境:可能為其他編碼

PHP 直接讀取輸出並按 UTF-8 解碼顯示/存儲,編碼不匹配即產生亂碼。

解決方案一:強制指定命令執行環境編碼(推薦)

function execUtf8(string $command): string {
    // 強制設定子進程 Locale 為 UTF-8
    $command = 'LANG=zh_TW.UTF-8 LC_ALL=zh_TW.UTF-8 ' . $command;
    
    $output = [];
    $returnVar = 0;
    exec($command, $output, $returnVar);
    
    if ($returnVar !== 0) {
        throw new RuntimeException("Command failed ($returnVar): $command");
    }
    return implode("\n", $output);
}

// 使用
try {
    $result = execUtf8('ls -la /path/with/chinese/中文目錄');
    echo $result; // 正常顯示中文
} catch (Throwable $e) {
    error_log($e->getMessage());
}

解決方案二:自動偵測並轉換編碼

function execAutoCharset(string $command): string {
    $output = [];
    $returnVar = 0;
    exec($command, $output, $returnVar);
    $raw = implode("\n", $output);
    
    if ($returnVar !== 0) {
        throw new RuntimeException("Command failed ($returnVar): $command");
    }
    
    // 偵測編碼(需安裝 mbstring、可選 iconv)
    $encoding = mb_detect_encoding($raw, ['UTF-8', 'GBK', 'BIG5', 'CP936', 'CP950'], true);
    if ($encoding && $encoding !== 'UTF-8') {
        $raw = mb_convert_encoding($raw, 'UTF-8', $encoding);
    }
    // 若偵測失敗,嘗試常見編碼強制轉換
    elseif (!$encoding) {
        $raw = @mb_convert_encoding($raw, 'UTF-8', 'GBK') 
            ?? @mb_convert_encoding($raw, 'UTF-8', 'BIG5')
            ?? $raw;
    }
    return $raw;
}

解決方案三:proc_open 精細控制(雙向管道、超時、環境變數)

function procExec(string $command, array $env = [], int $timeout = 30): array {
    $descriptors = [
        0 => ['pipe', 'r'],  // stdin
        1 => ['pipe', 'w'],  // stdout
        2 => ['pipe', 'w'],  // stderr
    ];
    
    $defaultEnv = ['LANG' => 'zh_TW.UTF-8', 'LC_ALL' => 'zh_TW.UTF-8'] + $env;
    $proc = proc_open($command, $descriptors, $pipes, null, $defaultEnv);
    
    if (!is_resource($proc)) {
        throw new RuntimeException("proc_open failed: $command");
    }
    
    // 非阻塞讀取
    stream_set_blocking($pipes[1], false);
    stream_set_blocking($pipes[2], false);
    
    $stdout = '';
    $stderr = '';
    $start = time();
    
    while (true) {
        $read = [$pipes[1], $pipes[2]];
        $write = $except = null;
        $n = stream_select($read, $write, $except, 0, 200000); // 0.2s
        
        if ($n > 0) {
            foreach ($read as $stream) {
                $data = fread($stream, 8192);
                if ($stream === $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("Command timeout ($timeout s): $command");
        }
    }
    
    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    $returnCode = proc_close($proc);
    
    // 編碼修正
    $stdout = fixEncoding($stdout);
    $stderr = fixEncoding($stderr);
    
    return ['stdout' => $stdout, 'stderr' => $stderr, 'code' => $returnCode];
}

function fixEncoding(string $str): string {
    $enc = mb_detect_encoding($str, ['UTF-8', 'GBK', 'BIG5', 'CP936', 'CP950'], true);
    if ($enc && $enc !== 'UTF-8') {
        return mb_convert_encoding($str, 'UTF-8', $enc);
    }
    return $str;
}

Windows 環境特別處理

function execWindows(string $command): string {
    // Windows cmd.exe 內部指令輸出為當前代碼頁(預設 cp936/950)
    // 使用 chcp 65001 切換至 UTF-8
    $command = 'chcp 65001 >nul && ' . $command;
    
    // 或使用 PowerShell(預設 UTF-8 輸出)
    $command = 'powershell -NoProfile -Command "' . addslashes($command) . '"';
    
    return execAutoCharset($command);
}

常見坑點與避坑

現象原因解決
中文檔名/路徑參數失效Shell 參數編碼與檔案系統不匹配PHP 端 escapeshellarg() 後傳遞,確保 Locale UTF-8
輸出截斷/不全緩衝區滿、進程未結束用 proc_open 非阻塞讀取、增大緩衝
殭屍進程未正確關閉管道、未 proc_close嚴格配對 open/close、使用 proc_terminate 超時殺掉
權限被拒Web 使用者無執行權限sudoers 配置特定命令 NOPASSWD、或改用守護進程

安全警示

  • 嚴禁直接拼接用戶輸入:務必使用 escapeshellarg()、escapeshellcmd()
  • 白名單驗證:只允許預定義命令、參數格式嚴格校驗
  • 最小權限:Web 用戶不可為 root,禁用 shell_exec、exec 等高危函數(disable_functions),改用任務佇列 + Worker 機制
  • 審計日誌:記錄所有命令執行:命令、參數、執行者、時間、結果

現代替代方案

  1. PHP 原生函數替代:glob()、scandir()、filesize()、filemtime()、mkdir()、unlink() 等,避免呼叫 Shell
  2. 任務佇列:Laravel Queue、Symfony Messenger、RabbitMQ、Redis Streams — Web 只入隊,Worker 安全執行
  3. 系統 API:需系統資訊用 sys_getloadavg()、disk_free_space()、php_uname() 等

總結

Shell 中文亂碼本質是編碼不匹配。最穩健做法:強制子進程 Locale 為 UTF-8(`LANG=zh_TW.UTF-8`),輔以 PHP 端 mb_detect_encoding + mb_convert_encoding 雙重保險。生產環境儘量避免直接執行 Shell,改用原生函數或佇列化異步處理。

copyright © 萬盛學電腦網 all rights reserved