php 5.3 fwrite() 期望参数 1 是资源错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11742682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php 5.3 fwrite() expects parameter 1 to be resource error
提问by user1425871
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?
我正在使用 wamp 服务器。我尝试写入文件,但它给出了这样的错误:“警告:fwrite() 期望参数 1 是资源,给出布尔值”。我该如何解决?
$file = 'file.txt';
if (($fd = fopen($file, "a") !== false)) {
fwrite($fd, 'message to be written' . "\n");
fclose($fd);
}
回答by phihag
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.
您的代码将(fopen($file, "a") !== false)(即布尔值)的结果分配给$fd.
回答by hakre
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.
还要了解您的语言:PHP 中的资源始终为真。
And know your brain: A double negation is complicated, always.
并了解您的大脑:双重否定总是很复杂。
回答by Palladium
The problem is in your ifcondition. PHP comparison binds more tightly than assignment, so the fopen !== falseis first evaluating to true, and then the trueis 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.
问题出在你的if情况。PHP 比较绑定比赋值更紧密,因此fopen !== false首先对 求值true,然后将true写入$fd. 您可以使用括号将其组合$fd = fopen($file, 'a')在一起,或者您可以将该部分从条件中取出并if ($fd !== false)改为为您的条件写作。
回答by Dennefyren
Put your !== falseoutside the ")"
把你的!== false外面的“)”
Like this:
像这样:
$file = 'file.txt';
if (($fd = fopen($file, "a")) !== false) {
fwrite($fd, 'message to be written' . "\n");
fclose($fd);
}
回答by Marc B
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.
并且您将!==比较的布尔结果分配给 $fd。
Either change the bracketing, or switch to the oroperator,w hich has a lower binding precedence:
要么更改括号,要么切换到or具有较低绑定优先级的运算符:
if (($fd = fopen(...)) !== false) {
^----------------^
or
或者
$fd = fopen(...) or die('unable to open file');

