Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append to file using ob_start

Tags:

file

php

append

I have looked for quite a while now, to see if it's possible to "append" to a file if using ob_start with PHP.

I have tried the following but did not work. Any way of achieving 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 borrowed the above example from another post on S.O.

like image 336
Funk Forty Niner Avatar asked Jun 05 '12 18:06

Funk Forty Niner


People also ask

What does Ob_start () function do?

The ob_start() function creates an output buffer. A callback function can be passed in to do processing on the contents of the buffer before it gets flushed from the buffer. Flags can be used to permit or restrict what the buffer is able to do.

What is Ob_start () in PHP w3schools?

Using ob_start allows you to keep the content in a server-side buffer until you are ready to display it. This is commonly used to so that pages can send headers 'after' they've 'sent' some content already (ie, deciding to redirect half way through rendering a page).

What is Ob_start () and Ob_end_flush () in PHP?

Delete an output buffer and send its contents to the browser: ob_start(); echo "This output will be sent to the browser"; ob_end_flush();

What is use of Ob_end_clean in PHP?

The ob_end_clean() function deletes the topmost output buffer and all of its contents without sending anything to the browser.


2 Answers

To append using file_put_contents() you can simply pass FILE_APPEND as the third argument:

file_put_contents($cacheFile, $content, FILE_APPEND);

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

like image 133
Ja͢ck Avatar answered Sep 28 '22 23:09

Ja͢ck


file_put_contents doesn't work that way. To append, you need to use fopen, fwrite and fclose manually.

$file = fopen($cacheFile, 'a+');
fwrite($file, $content);
fclose($file);
like image 33
Rocket Hazmat Avatar answered Sep 29 '22 01:09

Rocket Hazmat