Alex
Alex

Reputation: 5685

fwrite() error: supplied argument is not a valid stream resource. Why?

I have this code:

$file = '/path/to/file.txt';

if (($fd = fopen($file, "a") !== false)) {
    fwrite($fd, 'message to be written' . "\n");
    fclose($fd);
}

Why do I get the following warnings?

fwrite(): supplied argument is not a valid stream resource
fclose(): supplied argument is not a valid stream resource

Upvotes: 1

Views: 10822

Answers (2)

Jon
Jon

Reputation: 437336

Because you have a parenthesizing error. The code should read:

if (($fd = fopen($file, "a")) !== false) {

What the current code does is set $fd to the result of comparing the fopen return value with false, which is also false (assuming the fopen succeeds). In effect you have

if ($fd = false) {

which is self-explanatory and also testable (with var_dump).

The moral of the story: Don't assign values to variables inside if conditions. This is not 1980, and you are not programming in C. Just say no and make the core readable; it will love you for it.

Upvotes: 2

genesis
genesis

Reputation: 50966

Your if statement is wrong. Try

if (($fd = fopen($file, "a")) !== false) {

Because yours one is like

$fd = fopen($file, "a") !== false

Upvotes: 7

Related Questions