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);
}
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
.
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.
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.
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);
}
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');
来源:https://stackoverflow.com/questions/11742682/php-5-3-fwrite-expects-parameter-1-to-be-resource-error