Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

wampserver

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); 
} 
like image 706
user1425871 Avatar asked Jul 31 '12 14:07

user1425871


2 Answers

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.

like image 167
phihag Avatar answered Oct 06 '22 14:10

phihag


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.

like image 38
hakre Avatar answered Oct 06 '22 16:10

hakre