CodeIgniter 底下提供了 force_download 函數,讓使用者可以直接下載檔案,但是會遇到中文的問題,IE 底下開起來檔名會是亂碼,force_download(‘filename’, ‘data’) 如果 filename 使用中文,測試 FireFox 跟 Chrome 都是沒問題的,唯獨 IE 開起來就是有問題,所以麻煩請修改 helpers/download_helper.php 這隻程式。
if ( ! function_exists('force_download')) { function force_download($filename = '', $data = '') { if ($filename == '' OR $data == '') { return FALSE; } // Try to determine if the filename includes a file extension. // We need it in order to set the MIME type if (FALSE === strpos($filename, '.')) { return FALSE; } // Grab the file extension $x = explode('.', $filename); $extension = end($x); // Load the mime types @include(APPPATH.'config/mimes'.EXT); // Set a default mime if we can't find it if ( ! isset($mimes[$extension])) { $mime = 'application/octet-stream'; } else { $mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension]; } // Generate the server headers if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) { header('Content-Type: "'.$mime.'"'); header('Content-Disposition: attachment; filename="'.iconv('utf-8', 'big5', $filename).'"'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header("Content-Transfer-Encoding: binary"); header('Pragma: public'); header("Content-Length: ".strlen($data)); } else { header('Content-Type: "'.$mime.'"'); header('Content-Disposition: attachment; filename="'.$filename.'"'); header("Content-Transfer-Encoding: binary"); header('Expires: 0'); header('Pragma: no-cache'); header("Content-Length: ".strlen($data)); } exit($data); } }裡面利用了 iconv 把 utf-8 編碼,改成 big5,這樣在 IE 底下就不會出現問題了
header('Content-Disposition: attachment; filename="'.iconv('utf-8', 'big5', $filename).'"');
See also
- 來聊聊 PHP & JavaScript & CSS 的 Coding Style
- 為什麼我選擇使用 Laravel Framework?
- Laravel 搭配 Google, Facebook, Twitter 第三方 OAuth 認證
- 將 wordpress 強制使用 SSL 連線
- PHP 7 vs HHVM Benchmark 比較
- Laravel 50 個小技巧 + Laravel 5.2 新功能
- Laravel Homestead 支援 MySQL 5.7 和 Node 5.0
- PHP-FIG 新網站
- Laravel Homestead 支援 PHP 7
- Laravel 5.1 is released