Php 5.3 fwrite () expects parameter 1 to be a resource error

I am using a wamp server. I am trying to write to a file, but it gives the following error: "Warning: fwrite () expects parameter 1 to be a 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); 
} 
+5
source share
5 answers

Parentheses:

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

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

+11
source

Do one 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 simplify the code if you encounter an error message.

Also know your language: a resource in PHP always evaluates to true.

And know your brain: double negation is difficult, always.

+3
source

if. PHP , , fopen !== false true, true $fd. $fd = fopen($file, 'a') , if ($fd !== false) .

0

!== false ")"

:

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

. !== , =, :

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

!== $fd.

Either change the bracketing, or switch to an operator orthat has a lower binding priority:

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

or

$fd = fopen(...) or die('unable to open file');
0
source

All Articles