Uploading files in PHP is the most basic technical point, but there are many problems that need to be solved when going deeper. No, after uploading a Chinese file, the file name becomes garbled.
The following is the problem code, it is very simple:
1. Problem code
html part:
php part:
Uploaded a file named "test data.txt", oh ho, the file was uploaded, but the file name was garbled.
2. First test
Search for solutions online and find
changed to
It turns out that the return value of iconv function is false.
Check the function manual and find that the second parameter has special usage. A simple translation is that I can append //TRANSLIT or //IGNORE after the encoding. The former will convert the untranslatable characters into the closest characters. , the latter simply ignores characters that cannot be converted.
Try it:
Result:
bool(false) string(4) ".txt"
That is to say, Chinese characters cannot be converted, and there are not even close characters. It seems that the methods introduced online are not omnipotent.
3. The online introduction method fails, try again
Let me guess, maybe my system will cause garbled characters when creating Chinese files, so I rewrote the code:
The result was successfully created without garbled characters. . . In other words, it is not a system problem.
Think about it, my php file itself is utf8 encoded, then
This statement must use utf8 encoding, so the file name uploaded before must not be utf8 encoded, then the following statement must be wrong, because the source string itself is not utf8 encoded:
Use the function to check the encoding of the source string:
The result is CP936, that is, the source string encoding is GBK.
Try it
Problem solved, no more garbled characters
4. Another solution
In fact, there is another solution, which is to add
in the middle of the head tag of the html file.This keeps the encoding consistent and eliminates the need to transcode
5. The following is the conclusion
Using the iconv function can solve the problem of garbled Chinese file names when uploading. In fact, iconv can solve various garbled problems caused by inconsistent encoding.
Please check the encoding of the source string first when using the iconv function, unless you have already determined the encoding of the source string.
Try to ensure that all codes are encoded consistently, and only use the iconv function as a last resort.
To make a complaint, try not to use Chinese file names as file names saved on the server. Please convert the file names into your own file names (please convert even English file names).