Php fwrite/fclose 警告

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 一次处理打开、写入和关闭操作——不需要在它之后调用 fwritefclose。 (不仅不需要——它甚至没有任何意义,因为使用 file_put_contents 你甚至没有文件句柄开始。)

file_put_contents returns 写入的字节数,一个整数值——这就是你收到这些警告的原因。

当您使用 file_put_contents() 时,您根本不需要 fwrite()fclose()。来自 the docs for file_put_contents():

This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.

您的代码应如下所示:

$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()).但是您向它们传递了 return 由 file_put_contents() 编辑的值,这是一个整数。所以,你得到一个错误。