中文附件亂碼原因與其它php上傳中文名亂碼原因是一樣的就是編碼問題,因為php對中文支持不怎么樣我可以轉換編碼或直接重命令上傳的文件名即可.
熟悉PHP的朋友可能會很快解決問題,但不熟悉PHP代碼的朋友看過此文章相信一定能解決你的問題,接下來就分享下我的解決wordpress上傳中文文件名亂碼的心得吧~:
找到/wp-admin/includes/file.php這個文件,并最如下修改:
- function wp_handle_upload( &$file, $overrides = false, $time = null ) {
- //….
- // Move the file to the uploads dir
- //$new_file = $uploads['path'] . “/$filename”;
- // 修正中文文件名編碼問題
- $new_file = $uploads['path'] . “/” . iconv(“UTF-8″,”GB2312″,$filename);
- //…
- //return apply_filters( ‘wp_handle_upload’, array( ‘file’ => $new_file, ‘url’ => $url, ‘type’ => $type ), ‘upload’ );
- // 修正中文文件名編碼問題
- return apply_filters( ‘wp_handle_upload’, array( ‘file’ => $uploads['path'] . “/$filename”, ‘url’ => $url, ‘type’ => $type ) , ‘upload’);
修改完上傳至服務器,問題就解決啦,其實很簡單的啦,簡單的,把以下代碼添加到主題目錄functions.php 文件:
- function upload_file($filename) {
- $parts = explode(‘.’, $filename);
- $filename = array_shift($parts);
- $extension = array_pop($parts);
- foreach ( (array) $parts as $part)
- $filename .= ‘.’ . $part;
- if(preg_match(‘/[一-?]/u’, $filename)){
- $filename = md5($filename);
- }
- $filename .= ‘.’ . $extension;
- return $filename ;
- }
- add_filter(‘sanitize_file_name’, ‘upload_file’, 5,1);
上傳文件自動重命名的方法,下面以wordpress 3.2.1為例,打開wp-admin/includes/file.php文件,找到第326行這段代碼:
- // Move the file to the uploads dir
- $new_file = $uploads['path'] . "/$filename";
- if ( false === @ move_uploaded_file( $file['tmp_name'], $new_file ) )
- return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );
將其修改為:
- // Move the file to the uploads dir
- $new_file = $uploads['path'] . "/".date_i18n("YmdHis").floor(microtime()*1000).".".$ext;
- if ( false === @ move_uploaded_file( $file['tmp_name'], $new_file ) )
- return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );
保存,重新上傳文件,這樣,新上傳的文件,就會自動保存為“年月日時分秒+千位毫秒整數”的新文件名,并保存到相應的年月文件夾之下了,沒錯,就這么簡單,測試、通過,面對歐美客戶的英文外貿網站推薦使用此法.
新聞熱點
疑難解答
圖片精選