5

I am using wamp server. I try to write into the file but it is giving such error: "Warning: fwrite() expects parameter 1 to be resource, boolean given ". How can I solve it?

$file = 'file.txt';  
if (($fd = fopen($file, "a") !== false)) { 
  fwrite($fd, 'message to be written' . "\n");   
  fclose($fd); 
} 
hakre
  • 193,403
  • 52
  • 435
  • 836
user1425871
  • 149
  • 2
  • 5
  • 13

5 Answers5

11

Move parentheses:

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

Your code assigned the result of (fopen($file, "a") !== false) (i.e. a boolean value) to $fd.

phihag
  • 278,196
  • 72
  • 453
  • 469
3

Do one thing at a time, because there is no rush and enough space:

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

Especially make the code more easy in case you run into an error message.

Also know your language: A resource in PHP evaluates true, always.

And know your brain: A double negation is complicated, always.

hakre
  • 193,403
  • 52
  • 435
  • 836
0

The problem is in your if condition. PHP comparison binds more tightly than assignment, so the fopen !== false is first evaluating to true, and then the true is being written into $fd. You can use brackets to group $fd = fopen($file, 'a') together, or you can take that part out of the condition and write if ($fd !== false) for your condition instead.

Palladium
  • 3,723
  • 4
  • 15
  • 19
0

Put your !== false outside the ")"

Like this:

$file = 'file.txt';  
if (($fd = fopen($file, "a")) !== false) { 
  fwrite($fd, 'message to be written' . "\n");   
  fclose($fd); 
} 
Dennefyren
  • 344
  • 1
  • 2
  • 8
0

operator precedence is causing your problem. !== binds tighter than =, so your code is actually:

if ($fd = (fopen(...) !== false)) {
          ^--------------------^--

and you're assigning the boolean result of the !== comparison to $fd.

Either change the bracketing, or switch to the or operator,w hich has a lower binding precedence:

if (($fd = fopen(...)) !== false) {
    ^----------------^

or

$fd = fopen(...) or die('unable to open file');
Marc B
  • 356,200
  • 43
  • 426
  • 500