PHP同一函数内file_exists()仅生效一次的问题排查与解决
PHP 连续调用 file_exists() 出现检测失效的问题解决
我写了一个PHP函数,用于确认临时路径存在后,将两张不同的图片从临时路径重命名到永久路径。第一张图片的file_exists()检测正常通过,但第二张明明路径正确、文件存在,却始终无法通过检测。两段代码结构完全一致,仅文件名不同,找不到差异原因。
代码如下:
if(file_exists('temp/'.strtolower($option['image1']))){ $path1 = 'images/'.strtolower($option['image1']); // 上传目录 $tmp1 = 'temp/'.strtolower($option['image1']); if(rename($tmp1, $path1)){ $error = 0; }else{ $error = 4; } } if(file_exists('temp/'.strtolower($option['image2']))){ $path2 = 'images/'.strtolower($option['image2']); // 上传目录 $tmp2 = 'temp/'.strtolower($option['image2']); if(rename($tmp2, $path2)){ $error = 0; }else{ $error = 5; } }
问题原因
连续调用file_exists()本身没有问题,但PHP默认会缓存文件系统的状态信息(即stat缓存)。第一个操作中rename()修改了文件系统的状态,但后续的file_exists()会直接读取缓存的旧数据,导致无法正确检测到第二张文件的存在。
解决方案
在两个检测代码块之间调用clearstatcache(),清除PHP缓存的文件状态信息,让后续的文件系统函数能获取最新的文件状态:
if(file_exists('temp/'.strtolower($option['image1']))){ $path1 = 'images/'.strtolower($option['image1']); $tmp1 = 'temp/'.strtolower($option['image1']); if(rename($tmp1, $path1)){ $error = 0; }else{ $error = 4; } } // 清除文件状态缓存 clearstatcache(); if(file_exists('temp/'.strtolower($option['image2']))){ $path2 = 'images/'.strtolower($option['image2']); $tmp2 = 'temp/'.strtolower($option['image2']); if(rename($tmp2, $path2)){ $error = 0; }else{ $error = 5; } }
其他文件路径检查方法
除了file_exists(),还可以用以下方式检测文件:
is_file('temp/xxx'):专门检测目标是否是普通文件,避免误判目录或其他类型的文件节点realpath('temp/xxx'):返回文件的绝对路径,若文件不存在则返回false,同时能验证路径的有效性fopen('temp/xxx', 'r'):尝试以读模式打开文件,成功则说明文件存在(但大文件场景不推荐,会占用资源)
内容的提问来源于stack exchange,提问作者Catie Camastro
相关产品推荐
相关产品推荐

