user1121724
user1121724

Reputation: 21

fread(): supplied argument is not a valid stream resource

This is driving me a little mad, thought perhaps it could be a server config issue, but I have tried it on a different host and get the same issue.

I have narrowed it down and created a test script to rule everything out

<?php
$myFile = "test.txt";
$fh = fopen($myFile, 'r') || die("Couln't open file");
if ( $fh == true ) {
        echo "file handle valid<br>";
}
else {
        echo "file handle invalid<br>";
}
$theData = fread($fh, filesize($myFile)) || die("Couldn't read file");
echo $theData;
fclose($fh)|| die("Couldn't close file");
?>

When test.txt is missing I correctly get the die couldn't open file When test.txt is there I get

Warning: fread(): supplied argument is not a valid stream resource in

I have set test.txt to 777 to be sure

I also wrote this just to double check, which works fine

<?php
$data = file_get_contents('test.txt');
echo $data;
?>

Hopefully someone can shed some light on this for me.

Upvotes: 2

Views: 7177

Answers (2)

Marc B
Marc B

Reputation: 360672

You'e been bitten by operator precedence in PHP. || has a higher precedence than =, so you're actually assigning the result of a logical OR to $fh. Switching to

$fh = fopen($myFile, 'r') or die("Couln't open file");
                          ^^--- lower precedence logical or

will fix thigns up.

With or, the return value of fopen() is assigned to $fh, then the or die() is evaluated - if fopen() returns a file handle, the or will fail and code proceedes. If fopen fails, a boolean false is returned and the or die kicks in.

With ||, the value of fopen is logically ORred with the die call, and the result of that or (false) will be assigned to $fh.

Upvotes: 2

lanzz
lanzz

Reputation: 43168

$fh = fopen($myFile, 'r') || die("Couln't open file");

You are assigning a boolean expression to $fh, losing the actual file handle in the process. Try changing the above line to

($fh = fopen($myFile, 'r')) || die("Couln't open file");

Upvotes: 1

Related Questions