Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

warning feof() expects parameter 1 to be resource

My error logs are getting out of control with the two below errors

warning feof() expects parameter 1 to be resource

and

warning fread() expects parameter 1 to be resource

The bit of code responsible is

<?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);
?> 

I used this code for header downloads but its freaking out right now - before anyone asks what I have tried, I tried google but still don't fully understand the error message.

like image 747
Jeff Avatar asked May 14 '13 20:05

Jeff


3 Answers

fopen fails and returns false. false is not a resource, thus the warning.

You'd better test $fp before injecting it as a resource-like argument:

if(($fp = fopen($file, "r"))) {
    [...]
}
like image 87
ChristopheBrun Avatar answered Nov 03 '22 00:11

ChristopheBrun


I recently encountered this problem. The code ran perfectly on my local environment. But when it was loaded to the server, I got the message discussed in this thread. At the end, the problem was that the server is case-sensitive on file names, while my local environment is not. After having corrected the file name, everything started to work.

like image 32
user2916217 Avatar answered Nov 03 '22 00:11

user2916217


From PHP 7, you can now use the far more efficient method: -

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

echo "fileRecs=".$fileRecs;

See http://php.net/manual/en/class.splfileobject.php

like image 1
Steve Hodgkiss Avatar answered Nov 02 '22 22:11

Steve Hodgkiss