【问题标题】:php: if (file_exists($file)) returns true for some files, false for othersphp: if (file_exists($file)) 对某些文件返回 true,对其他文件返回 false
【发布时间】:2018-10-31 13:42:49
【问题描述】:

我很难过。我正在编写一个脚本以从 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();
}

?>

所以如果我在我的服务器上浏览到以下 URL:

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 看到这个(大)文件存在?

【问题讨论】:

  • 您要添加此文件吗?有时我遇到了您必须使用以下命令清除统计缓存的问题:php.net/manual/en/function.clearstatcache.php,但我不能说这是您的问题。
  • 您在哪里托管您的网站?如果它托管在 UNIX 机器上,则文件区分大小写。如果您无法手动导航到那里,这很好地表明您实际上可能上传了一个文件扩展名不同的文件。
  • Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB. -php.net/manual/en/function.file-exists.php 所以
  • header('X-Sendfile: $file'); 应该是 header("X-Sendfile: $file");
  • 它可能会发出带有一些解释的 E_WARNING

标签: php if-statement file-exists


【解决方案1】:

基于@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() 的文件。

【讨论】:

    猜你喜欢
    • 2011-06-05
    • 2015-09-14
    • 2013-02-28
    • 2014-01-02
    • 1970-01-01
    • 2012-09-02
    • 2016-01-13
    • 2011-10-19
    • 2017-08-15
    相关资源
    最近更新 更多