Page 1 of 1

ob_start() stopping?

Posted: Fri Mar 25, 2011 11:23 pm
by changoz
Hi,
sorry because of my bad english.

I read about caching php pages using ob_start() function.

Im using this code:

Code: Select all

<?php
$cachefile = 'path_to_cache/'. basename($_SERVER['REQUEST_URI']);
$cachetime = 120 * 60; // 2 hours
if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile))) 
{
include($cachefile);
exit;
}
ob_start(); 
?> 

Content (html+php)

<?php
$fp = fopen($cachefile, 'w'); // open the cache file for writing
fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file
fclose($fp); // close the file
ob_end_flush(); // Send the output to the browser
?> 
This is working fine as i see the cached files stored in my cache folder.

The problem is when i add this code in my content section:

Code: Select all

<?php 
require('/path_to_wp-load.php'); 
$querywp = 'showposts=5&cat=' . $var1 . ',' .$var2 . '&orderby=date&order=DESC'; 
query_posts( $querywp );  if (have_posts()) : while (have_posts()) : the_post(); 
?>
Im displaying some custom Wordpress posts inside my page.

And it works fine, but only the first time i see the page.
When i reload it, i see a broken page.

The cached page is stored, but size is less than the normal one; checking the code, i see that the ob_start function seems to start buffering just after that piece of wordpress code, like if the previous lines didnt exist or the wordpress code was causing to 'empty' the already buffered content.

Anyone can help me with this?

Thanks a lot

Re: ob_start() stopping?

Posted: Sat Mar 26, 2011 12:36 pm
by Weirdan
like if the previous lines didnt exist or the wordpress code was causing to 'empty' the already buffered content.
It's quite possible, and since there could be any number of hooks assigned to post display, it's not going to be easy to find out where buffers might be flushed.

Re: ob_start() stopping?

Posted: Sat Mar 26, 2011 1:10 pm
by changoz
Well, thanks for your reply.

Do i have any other way to cache my pages without using buffers?

Re: ob_start() stopping?

Posted: Sat Mar 26, 2011 6:57 pm
by Weirdan
It seems you may prevent your top-level buffer from being deleted by issuing ob_start() of the following form:

Code: Select all

ob_start(null, 0, false);
It will also cause any code that tries to delete that buffer to issue notices, so you would be able to track it down.

Re: ob_start() stopping?

Posted: Sat Mar 26, 2011 7:32 pm
by changoz
Thanks for your research/knowledge Weirdan,
altought i resolved by changing the way i call the wordpress posts, i will give it a try to see what happens.

Regarding the wordpress, i replaced the native wordpress function by making the sql query to the wp database and the buffer works fine.

I really appreciate your help.

Cheers.
Cristian