Home  >  Article  >  Backend Development  >  PHP中file_exists函数不支持中文名的解决方法_php技巧

PHP中file_exists函数不支持中文名的解决方法_php技巧

WBOY
WBOYOriginal
2016-05-16 20:39:11941browse

一般来说PHP中常使用file_exists()判断某个文件或者文件夹是否存在,如果存在则返回true,否则返回false。但是该函数在网页使用UTF8编码的情况下,对于中文的文件名或者文件夹名不能返回正确值,始终返回false。经测试之后得出解决方法,分析造成这一情况的原因应该是编码不同而导致的PHP不能正确判断。

下面这段代码是不能够返回正确值的代码,无论文件是否在都返回不在:

<?php;
$file="/attachment/21/0/中文.rar";
$newfile = dirname(__FILE__).$file;

echo file_exists($newfile);
?>

经过测试之后,增加了一句将UTF8编码转换为GB2312编码的语句,就可以正确判断了:

<?php
$file="/attachment/21/0/中文.rar";
$newfile = dirname(__FILE__).$file;

$file=iconv('UTF-8','GB2312',$file);

echo file_exists($newfile);
?>
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