warning feof()期望参数1是资源

时间:2013-05-14 20:43:36

标签: php error-handling

我的错误日志失控,发生以下两个错误

warning feof() expects parameter 1 to be resource

warning fread() expects parameter 1 to be resource

负责的代码是

<?php
    $file = '../upload/files/' . $filex;
    header("Content-Disposition: attachment; filename=" . urlencode($file));
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header("Content-Description: File Transfer");
    header("Content-Length: " . filesize($file));
    flush(); // this doesn't really matter.

    $fp = fopen($file, "r");
    while (!feof($fp)) {
        echo fread($fp, 65536);
        flush(); // this is essential for large downloads
    }
    fclose($fp);
?> 

我使用此代码进行标题下载,但它现在吓坏了 - 在有人询问我尝试过之前,我尝试了google但仍然不完全理解错误消息。

3 个答案:

答案 0 :(得分:5)

fopen失败并返回false。 false不是资源,因此是警告。

在将其作为类似资源的参数注入之前,最好测试$ fp:

if(($fp = fopen($file, "r"))) {
    [...]
}

答案 1 :(得分:0)

我最近遇到过这个问题。代码在我的本地环境中完美运行。但当它被加载到服务器时,我得到了这个线程中讨论的消息。最后,问题是服务器对文件名区分大小写,而本地环境则不区分大小写。纠正文件名后,一切都开始起作用了。

答案 2 :(得分:0)

从PHP 7开始,您现在可以使用效率更高的方法:-

$fileRecs = 0;
$file = new SplFileObject('textfile.txt, 'r');
$file->seek(PHP_INT_MAX);
$fileRecs = $File->key() + 1;

echo“ fileRecs =”。$ fileRecs;

请参见http://php.net/manual/en/class.splfileobject.php