Home >Backend Development >PHP Tutorial >Solution to the problem that the file_exists function in PHP cannot detect file names containing Chinese characters

Solution to the problem that the file_exists function in PHP cannot detect file names containing Chinese characters

WBOY
WBOYOriginal
2016-07-29 08:55:471731browse

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=&#39;../uploads/file/中文.pdf&#39;;    //  在../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= &#39;中文.pdf&#39;;    //  在../uploads/file/文件夹中  中文.pdf   实际存在
   $file=iconv(&#39;UTF-8&#39;,&#39;GB2312&#39;,$file);
   echo file_exists(&#39;../uploads/file/&#39; . $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=&#39;../uploads/file/中文.pdf&#39;;    //  在../uploads/file/文件夹中  中文.pdf   实际存在
    $file=iconv(&#39;UTF-8&#39;,&#39;GB2312&#39;,$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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn