php文件上傳中文亂碼的解決辦法:首先打開相應(yīng)的PHP文件;然后通過“iconv("UTF-8", "gbk",$name)”方法對(duì)文件名進(jìn)行強(qiáng)制轉(zhuǎn)碼,將UTF8轉(zhuǎn)換成gbk即可。
推薦:《PHP視頻教程》
關(guān)于PHP上傳文件和中文名亂碼情況
在前端HTML頁面,表單如下
Upload.html
<!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <form action="upload.php" method="post" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="2621114"> <input type="file" required name="upload_file"> <input type="submit" value="提交"> </form> </body> </html>
注意
enctype="multipart/form-data"一定要寫,這是告訴瀏覽器你在上傳什么東西
<input type="hidden" name="MAX_FILE_SIZE" value="2621114"> 前端設(shè)置文件大最大值
后端upload.php
<?php if (is_uploaded_file($_FILES['upload_file']['tmp_name'])){ $upfile = $_FILES['upload_file']; //print_r($upfile); $name = $upfile['name'];//獲取文件名 $type = $upfile['type'];//文件類型 $size = $upfile['size'];//文件大小 $tmp_name = $upfile['tmp_name'];//服務(wù)器存儲(chǔ)的臨時(shí)名稱 $error = $upfile['error'];//錯(cuò)誤信息 switch ($type){ case 'image/png': $ok=1; break; case 'image/jpg': $ok=1; break; case 'image/jif': $ok=1; break; case 'image/jpeg': $ok=1; break; } if ($ok && $error == 0){ move_uploaded_file($tmp_name,'./upload/'.iconv("UTF-8", "gbk",$name)); echo '文件上傳成功'; }else{ echo '文件上傳失敗'; } }
上傳時(shí),PHP收到關(guān)于該文件的信息數(shù)組,這些信息可以在$_FILES這個(gè)超級(jí)全局?jǐn)?shù)組中找到。
如:如果表單中的文件輸入框名字為upload_file,那么關(guān)于該文件的所有信息都包含在數(shù)組$_FILES['upload_file']里面。
is_uploaded_file — 判斷文件是否是通過 HTTP POST 上傳的
move_uploaded_file — 將上傳的文件移動(dòng)到新位置
bool move_uploaded_file ( string $filename , string $destination )
當(dāng)遇到中文文件名的時(shí)候,對(duì)文件名進(jìn)行強(qiáng)制轉(zhuǎn)碼iconv("UTF-8", "gbk",$name),將UTF8轉(zhuǎn)換成gbk,這樣就不會(huì)出現(xiàn)亂碼了