-2

I have the following code fragment which works btw:

  $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);

But the following warnings get logged when running it:

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

Probably my logic is wrong here. Maybe someone can shed some light here?

Ivan
  • 1,274
  • 16
  • 22

2 Answers2

1

file_put_contents handles the operations open, write and close all in one go – there is not need to call fwrite and fclose after it. (Not only no need – it doesn’t even make any sense, because with file_put_contents you do not even have a file handle to begin with.)

file_put_contents returns the number of bytes written, an integer value – and that’s why you get those warnings.

CBroe
  • 91,630
  • 14
  • 92
  • 150
1

You don't need fwrite() or fclose() at all when you use file_put_contents(). From the docs for file_put_contents():

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

Your code should look like:

$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);

As for why you get errors with your current code: fwrite() and fclose() expect the first parameter to be a resource (the type of return value you get from fopen()). But you're passing them the value returned by file_put_contents(), which is an integer. So, you get an error.

elixenide
  • 44,308
  • 16
  • 74
  • 100
  • after first line should be like `if (!$file) die('Failed to write ../offer/work/uploads/'.$php_id.'.html');` – ekerner Apr 09 '18 at 15:34
  • @ekerner That would make the code better, but I wasn't trying to write better code for OP here; I was trying to demonstrate the solution to OP's problem. – elixenide Apr 09 '18 at 15:41