Home > Article > Backend Development > How to solve the problem of garbled characters when uploading Chinese in PHP
Method to solve the problem of garbled Chinese characters uploaded by PHP: first add [enctype="multipart/form-data"] to the corresponding file; then use [iconv("UTF-8", "gbk" ,$name)】Forcibly transcode the file name.
Recommended: "PHP Video Tutorial"
About PHP upload files and garbled Chinese names
In the front-end HTML page, the form is as follows
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>
Note
enctype="multipart/form-data" must be written, this is to tell the browser What are you uploading? When uploading via 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'];//服务器存储的临时名称 $error = $upfile['error'];//错误信息 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 '文件上传失败'; } }
, PHP receives an array of information about the file. This information can be found in the super global array $_FILES.
For example: If the name of the file input box in the form is upload_file, then all information about the file is included in the array $_FILES['upload_file'].
is_uploaded_file — Determine whether the file was uploaded via HTTP POST
move_uploaded_file — Move the uploaded file to a new location
bool move_uploaded_file ( string $filename , string $destination )
When encountering a Chinese file name, force transcode iconv("UTF-8", "gbk",$name) on the file name and convert UTF8 to gbk, so that there will be no garbled characters.
The above is the detailed content of How to solve the problem of garbled characters when uploading Chinese in PHP. For more information, please follow other related articles on the PHP Chinese website!