Shell 命令輸出編碼取決於終端機環境編碼(通常為系統 Locale),而 PHP 腳本內部編碼通常為 UTF-8。常見組合:
LANG=zh_TW.UTF-8 或 zh_CN.UTF-8 → 輸出 UTF-8cp936 (GBK) / cp950 (Big5) → 輸出 ANSIPHP 直接讀取輸出並按 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;
}
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;
}
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()shell_exec、exec 等高危函數(disable_functions),改用任務佇列 + Worker 機制glob()、scandir()、filesize()、filemtime()、mkdir()、unlink() 等,避免呼叫 Shellsys_getloadavg()、disk_free_space()、php_uname() 等Shell 中文亂碼本質是編碼不匹配。最穩健做法:強制子進程 Locale 為 UTF-8(`LANG=zh_TW.UTF-8`),輔以 PHP 端 mb_detect_encoding + mb_convert_encoding 雙重保險。生產環境儘量避免直接執行 Shell,改用原生函數或佇列化異步處理。