php 5.3 fwrite() expects parameter 1 to be resource error

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

preguntado el 31 de julio de 12 a las 15:07

As per PHP documentation For portability, it is strongly recommended that you always use the 'b' flag when opening files with fopen() intenta hacerlo $fb = fopen($file, 'ab') -

You placed the parentheses wrong. -

5 Respuestas

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.

Respondido 31 Jul 12, 15:07

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.

Respondido 31 Jul 12, 16:07

El problema está en tu if condition. PHP comparison binds more tightly than assignment, so the fopen !== false is first evaluating to true, y luego el 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.

Respondido 31 Jul 12, 15:07

Poner su !== false outside the ")"

Me gusta:

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

Respondido 31 Jul 12, 15:07

operator precedence is causing your problem. !== se une más fuerte que =, 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');

Respondido 31 Jul 12, 15:07

or $fd=fopen(..); if($fd) {...} - muy bien

Por favor no die ... (although a cynic could argue that if you're writing in php, you don't care about proper exception handling anyways) - Phihag

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.