Last updated on April 4th, 2022 at 08:40 am

PHP Output buffering using ob_start

Output buffering using ob_start in php and saving it to a variable, This is a very good feature available in PHP mainly when we want to output an HTML website. Using ob_start you can basically save everything to a variable and print it later on.

In the below script we are saving everything inside variable $output using ob_get_contents()

Using ob_get_clean() you can get current buffer contents and delete current output buffer. Below script just create a cooking and print it. Along with that it print the content of the output buffer.

<?php ob_start(); ?>
Hello world, <?php echo "My Website"; ?>
<br>Thank you.
<?php
$output = ob_get_contents();
ob_get_clean();
echo "Just a simple cookie set script<p>";
if(isset($_COOKIE["test1"]))
{
echo $_COOKIE["test1"];
}
else
{$cookie_name = "test1";
$cookie_value = "Doe";
setcookie($cookie_name, $cookie_value, time()+1800, "/");
        echo "Cookie not set, refresh the page";
}
echo "<p>-------GETTING CONTENT FROM OB-------";
echo "<p>".$output;
?>

Leave a Reply

Your email address will not be published. Required fields are marked *