fwrite()错误:提供的参数不是有效的流资源。为什么?

时间:2011-10-19 13:20:57

标签: php warnings

我有这段代码:

$file = '/path/to/file.txt';

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

为什么会收到以下警告?

fwrite(): supplied argument is not a valid stream resource
fclose(): supplied argument is not a valid stream resource

2 个答案:

答案 0 :(得分:7)

您的if语句错误。尝试

if (($fd = fopen($file, "a")) !== false) {

因为你的一个就像

$fd = fopen($file, "a") !== false

答案 1 :(得分:2)

因为您有一个括号错误。代码应为:

if (($fd = fopen($file, "a")) !== false) {

当前代码将$fd设置为将fopen返回值与false进行比较的结果,false也是fopen(假设if ($fd = false) { 成功)。实际上你有

var_dump

这是不言自明的,也是可测试的(if)。

故事的寓意:不要为{{1}}条件中的变量赋值。这不是1980年,你不是用C编程。只要说不,让核心可读;它会爱你的。