Home >Backend Development >PHP Tutorial >Solution to the problem that the file_exists function in PHP cannot detect file names containing Chinese characters
File_exists() is generally used in PHP to determine whether a file or folder exists. If the file or folder exists, it returns true, and if it does not exist, it returns false. Today when implementing the file download function, I found that when the web page uses UTF8 encoding, the function cannot detect whether the file containing Chinese exists and always returns false. After a long time of modification, I discovered that it was because the full path was not encoded. Simply transcoding the file name was not enough.
The following code cannot detect whether a file containing Chinese exists, and returns false regardless of whether the file exists:
<?php; $file='../uploads/file/中文.pdf'; // 在../uploads/file/文件夹中 中文.pdf 实际存在 echo file_exists($file); //输出为false ?>
Just transcoding the file name will not work. This is the situation I encountered, and I need to put [ Path + file name] can be transcoded together
<?php $file= '中文.pdf'; // 在../uploads/file/文件夹中 中文.pdf 实际存在 $file=iconv('UTF-8','GB2312',$file); echo file_exists('../uploads/file/' . $file); //输出为false ?>
In fact, as long as the file path and file name are converted from UTF8 encoding to GB2312 encoding, after the improvement, you can accurately judge:
<?php $file='../uploads/file/中文.pdf'; // 在../uploads/file/文件夹中 中文.pdf 实际存在 $file=iconv('UTF-8','GB2312',$file); echo file_exists($file); //输出为true ?>
The above introduces the solution to the problem that the file_exists function in PHP cannot detect file names containing Chinese characters, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.