Php fwrite/fclose warning


Php fwrite/fclose warning

我有以下代码片段可以正常工作:

  $txt = "<?php include 'work/uploads/".$php_id.".html';?>";
  $slot = file_put_contents('../offer/slots.php', $txt.PHP_EOL , FILE_APPEND);
  fwrite($slot, $txt);
  fclose($slot);
  $theCounterFile = "../offer/count.txt";
  $oc = file_put_contents($theCounterFile, file_get_contents($theCounterFile)+1);
  fwrite($oc);
  fclose($oc);

但是在运行它时会记录以下警告:

Line 81 : fwrite() expects parameter 1 to be resource, integer given
Line 82 : fclose() expects parameter 1 to be resource, integer given
Line 85 : fwrite() expects at least 2 parameters, 1 given
Line 86 : fclose() expects parameter 1 to be resource, integer given

可能我的逻辑在这里是错误的。也许有人可以在这里提供一些启示?

使用 file_put_contents() 时根本不需要fwrite()fclose()。来自file_put_contents()的文档:

此函数与依次调用fopen()fwrite()fclose()将数据写入文件相同。

您的代码应如下所示:

$file = fopen("../offer/work/uploads/".$php_id.".html","w");
fwrite($file,$data); // Note: you could use file_put_contents here, too...
fclose($file);
$txt = "<?php include 'work/uploads/".$php_id.".html';?>";
$slot = file_put_contents('../offer/slots.php', $txt.PHP_EOL , FILE_APPEND);
$theCounterFile = "../offer/count.txt";
$oc = file_put_contents($theCounterFile, file_get_contents($theCounterFile)+1);

至于为什么当前代码会出现错误:fwrite()fclose()期望第一个参数是资源(您从fopen()获得的返回值的类型(。但是你正在向他们传递 file_put_contents() 返回的值,这是一个整数。所以,你得到一个错误。

file_put_contents一次性处理打开、写入和关闭操作 - 无需调用fwrite并在它之后调用fclose。(不仅不需要 - 它甚至没有任何意义,因为有了file_put_contents,你甚至没有文件句柄开始。

file_put_contents返回写入的字节数,一个整数值 - 这就是您收到这些警告的原因。