How to solve the problem of garbled file names obtained by php?
I think many friends will encounter such a problem when developing the upload function of UTF8-encoded PHP. When uploading a file with a Chinese file name, the file name will become garbled. In fact, we You can use the iconv function to re-encode the file name to solve the problem.
The php file uses UTF-8 encoding. If you guessed correctly, APACHE should use GBK for processing. After thinking about this problem, I went to search for relevant tutorials and simply found the iconv function.
Function prototype: string iconv (string in_charset, string out_charset, string str)
Usage example: $content = iconv("GBK", "UTF-8" , $content);
The function of this example is to convert $content from GBK to UTF-8 encoding.
Key code for garbled code problem:
Copy code The code is as follows:
$name=iconv("UTF-8","gb2312", $name);
In addition to solving the problem of Chinese garbled characters in uploaded files, we can also rename the uploaded files.
Example
Copy the code as follows:
$sFileName = “sda.php”; $sOriginalFileName = $sFileName; $sExtension = s str($sFileName, (strrpos($sFileName, ‘.’) + 1));//找到扩展名 $sExtension = strtolower($sExtension); $sFileName = date(“YmdHis”).rand(100, 200).”.”.$sExtension; //这样就是我们的新文件名了,全数字的不会有乱码了哦。
The following are some additions:
Solution for php uploading garbled Chinese file names
Copy the code as follows:
$filepath=”upload/”; $name=$filepath.$_FILES[“upfile”][“name”]; while(file_exists($name)){ $temp=explode(“.”,$name);//分割字符串 $name=$temp[0].”0″.”.”.$temp[1];//主文件名后面加0 }
Copy the code as follows:
//iconv() function is the key
if(move_uploaded_file($_FILES[“upfile”][“tmp_name”],iconv(“UTF-8″,”gb2312”,$name))){//处理…}
My PHP encoding is UTF-8, the reason may be It's because the operating system is GBK!
Note: My server is windows xp, apache, and it is estimated that the xp character set is gbk. Because my PHP code is saved in UTF-8 format, garbled characters will appear when naming the file name, so you can use the iconv() function to convert the original UTF-8 format file name to gbk format.
Solution to garbled Chinese file names in php utf8 encoding The file name will become garbled. We can use the iconv function to re-encode the file name and solve the problem.
Copy code The code is as follows:
header("Content-Type:text/html;charset=utf-8"); $submit = $_POST[‘submit‘]; if(isset($submit) && trim($submit) != ‘‘){ $file = $_FILES[‘file‘]; if(isset($file[‘tmp_name‘])){ $name = iconv(‘utf-8‘,‘gb2312‘,$file[‘name‘]); //利用Iconv函数对文件名进行重新编码 if(move_uploaded_file($file[‘tmp_name‘],$name)){ echo ‘文件上传成功!‘; echo ‘图片信息:‘; print_r($file); } } }
The above is the detailed content of How to solve the problem of garbled file name obtained by php. For more information, please follow other related articles on the PHP Chinese website!