php:if(file_exists($ file))对于某些文件返回true,对其他文件返回false

时间:2018-05-21 21:09:38

标签: php if-statement file-exists

我很难过。我正在整理一个脚本来从URL获取PATH_INFO并使用它来从服务器上的特定目录发送文件。

在服务器上:

ll /path/to/directory/with/my/files/
total 7195210
-rwxrwx--- 1 user group  716852833 May 11 15:17 file1.7z
-rwxrwx--- 1 user group 1000509440 May 11 15:31 file2.cxarchive
-rwxrwx--- 1 user group 5878056960 May 11 17:32 file3.ISO

我的代码中有一个if (file_exists($file)块,它适用于file1和file2,但是file3,位于完全相同的位置,它会触发else语句,表明PHP认为该文件不存在。

<?php
//get file name from URL, trim leading slash.
$filename = ltrim($_SERVER['PATH_INFO'], "/");

//sanitize the filename
if(preg_match('/\.\.|[<>&~;`\/$]/', $filename)) {
    trigger_error("Invalid path '$filename' attempted by $user");
    show_error();
}

//prepend my files directory to the filename.
$file = '/path/to/directory/with/my/files/' . $filename;

//send file
if (file_exists($file)) {
    echo '<pre>The file '; print_r($file); echo ' exists.</pre>';
    header('X-Sendfile: $file');
    exit;
} else {
    echo '<pre>the file does not exist?</pre>';
    show_error();
}

?>

所以如果我浏览我服务器上的以下网址:

https://my.server.com/script.php/file1.7z

文件file1.7z存在。

https://my.server.com/script.php/file2.cxarchive

文件file2.cxarchive存在。

https://my.server.com/script.php/file3.ISO

该文件不存在?

一堆测试结果可能是文件很大的罪魁祸首。我得到了发送文件内存限制是一个问题,但我怎么让PHP看到这个(大)文件存在?

1 个答案:

答案 0 :(得分:0)

基于@ user3783243的评论:

  

由于PHP的整数类型已签名且许多平台使用32位整数,因此某些文件系统函数可能会为大于2GB的文件返回意外结果。

     

- https://secure.php.net/manual/en/function.file-exists.php

所以我编写了自己的file_exists函数,没有这个限制(基于comment on that page):

function fileExists($file){
return (@fopen($file,"r")==true);
}

然后,将其插入代码中:

//send file
if (fileExists($file)) {    //remove underscore, cap E
echo '<pre>The file '; print_r($file); echo ' exists.</pre>';
header("X-Sendfile: $file");    //fixed, thanks @jamie
exit;
} else {
echo '<pre>the file does not exist?</pre>';
show_error();
}

成功!存在的文件(甚至是大文件),不运行show_error()的文件。