在 Windows 環境下,PHP 腳本以 UTF-8 編碼儲存、網頁輸出也設為 UTF-8 時,使用 fopen() 建立中文檔名檔案,檔名往往會變成亂碼。根本原因是:**Windows 檔案系統預設使用 ANSI 編碼(繁體中文環境為 Big5/CP950,簡體為 GBK/CP936),而非 UTF-8。**
早期開發者常嘗試將所有 PHP 檔案、include 檔案、HTML meta charset 全部改為 ANSI/GBK。雖能解決檔名亂碼,但會導致:
保持專案全域 UTF-8,僅在呼叫檔案系統函數(fopen、mkdir、unlink、rename 等)前,將檔名從 UTF-8 轉為系統編碼(GBK/Big5)。
<?php
/**
* 將 UTF-8 檔名轉為系統相容編碼(Windows 簡體預設 GBK,繁體 Big5)
* @param string $filename UTF-8 編碼檔名
* @return string 系統編碼檔名
*/
function toSystemFilename(string $filename): string
{
// 簡體中文 Windows 使用 GBK(或 CP936)
// 繁體中文 Windows 使用 Big5(或 CP950)
// 可透過 PHP_OS_FAMILY 或環境變數判斷
$targetEncoding = 'GBK'; // 或 'BIG-5', 'CP950'
return iconv('UTF-8', $targetEncoding . '//IGNORE', $filename);
}
// 實際使用範例
$utf8Name = "測試報表_{$id}.html";
$sysName = toSystemFilename($utf8Name);
$fp = fopen($sysName, 'w');
if ($fp) {
fwrite($fp, $content);
fclose($fp);
echo "建立成功:$utf8Name";
} else {
echo "建立失敗";
}
?>
<?php
// test.php
$rows = [
['標題一', '內容一'],
['標題二', '內容二'],
];
$template = file_get_contents('template.htm'); // UTF-8 編碼模板
foreach ($rows as $id => [$title, $content]) {
$pageName = "測試_{$id}.html";
$pageName = iconv('UTF-8', 'GBK//IGNORE', $pageName); // 關鍵步驟
$html = str_replace(['{title}', '{content}'], [$title, $content], $template);
$fp = fopen($pageName, 'w');
fwrite($fp, $html);
fclose($fp);
}
echo "批次建立完成";
?>
<?php
class FileSystemHelper
{
public static function normalizePath(string $path): string
{
if (DIRECTORY_SEPARATOR === '\\') { // Windows
// 嘗試偵測系統代碼頁,預設 GBK
$encoding = 'GBK';
// 可透過 `chcp` 指令或 registry 進一步偵測
return iconv('UTF-8', $encoding . '//TRANSLIT', $path);
}
return $path; // Linux/Unix 通常直接支援 UTF-8
}
public static function fopen(string $filename, string $mode): resource|false
{
return fopen(self::normalizePath($filename), $mode);
}
public static function mkdir(string $dir, int $mode = 0777, bool $recursive = true): bool
{
return mkdir(self::normalizePath($dir), $mode, $recursive);
}
// ... 同理封裝 unlink, rename, file_get_contents, file_put_contents 等
}
?>
iconv 若遇到無法轉換的字元會拋出 E_NOTICE 並返回 false,建議加 //IGNORE 或 //TRANSLIT 後綴。\ / : * ? " < > |)會導致建立失敗,需預先過濾或替換。move_uploaded_file() 處理上傳檔案時,$_FILES['file']['name'] 為原始檔名(瀏覽器編碼不一),建議**捨棄原檔名**,改用 UUID + 副檔名儲存,資料庫另存原始檔名供下載時使用。「專案統一 UTF-8,邊界處轉編碼」是處理中文檔名亂碼的黃金法則。透過 iconv 針對檔名參數單獨轉碼,既保持代碼庫編碼一致性,又能相容 Windows 檔案系統,是最經濟、可維護的解決方案。