How to add file to ob_start file

I searched for quite a while to see if it is possible to “add” to the file if you use ob_start with PHP.

I tried the following but did not work. Any way to achieve this?

<?php

$cacheFile = 'file.txt';

if ( (file_exists($cacheFile)) && ((fileatime($cacheFile) + 600) > time()) )
{
$content = file_get_contents($cacheFile);
echo $content;
} else
{
ob_start();
// write content
echo '<h1>Hello world</h1>';
$content = ob_get_contents();
ob_end_clean();
file_put_contents($cacheFile,$content,'a+'); // I added the a+
echo $content;
}
?>

I took this example from another post on SO

+5
source share
2 answers

file_put_contentsdoes not work. To add, you need to use fopen, fwriteand fclosemanually.

$file = fopen($cacheFile, 'a+');
fwrite($file, $content);
fclose($file);
+4
source

To add file_put_contents(), you can simply pass FILE_APPENDas the third argument:

file_put_contents($cacheFile, $content, FILE_APPEND);

It can also be used to apply file locking using the binary OR operator, for example. FILE_APPEND | LOCK_EX.

+6
source

All Articles