Ob_flush , ob_start ,ob_get_contents, ob_end_clean, ob_end_flush with real time example

Let see the Functions first then will see the real world example

ob_start is to start buffer the output 

ob_flush is to flush the buffered output (that means it will delivers the output here which is buffered when the ob_start is initiated)

ob_end_flush is to flush and ends the buffering

ob_end_clean is to clean the buffered output content ends the buffering

ob_get_contents is to get the buffered output content

 

let see the basic example

<?php

ob_start();

echo "Hello";
echo "World";

$out = ob_get_contents();



/* when i remove this comment of ob_end_flush() will show the output  and stop output buffer, it will echo hello and world */ 

// ob_end_flush(); // ends flush, 


/* when i remove this comment of ob_end_clean() it will clean  the output and stop buffers  */ 
 
// ob_end_clean(); // if I add this line above ob_end_flush then ob_end_flush will not flush output because output buffer will be cleared here.


var_dump($out); // print the dump of the variable $out 

?>

Now let see where it will used in real time world

I'm going create one file caching system using ob_flush and start

<?php

global $file, $output;

$filename = basename($_SERVER["SCRIPT_FILENAME"], '.php');
$file = $filename.'.html';

if(file_exists($file)) {
   $output = file_get_contents($file);
}else {
  generate_output();	
}




echo $output;



function generate_output() {
    global $file, $output;

    ob_start();

    echo "Realtime example of ob_flush, now Im going to cache this output in somefile <br/>";
    
    echo "This output will be generated only when the html file is not exist see the above condition at top <br/>";

    echo "it will check for HTML File which is exist with this current filename if the HMTL is not exist then it will execute this function and generate html file<br/>";

    echo "This Beginning HTML file redirection can be handled in .htaccess also in a way that if html file is not exist then look for php file <br/>";

    $time = date('Y-m-d H:i:s');
	
    echo "Hello World ".$time;


	$output = ob_get_contents();

 
   ob_end_clean();
   ob_end_flush();

   $file_ob = fopen($file, 'w');
   fwrite($file_ob,$output);
   fclose($file_ob);
}

Hope it will be useful for someone.