PHP Web Fundamentals Buffering Output to the Browser - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Web Fundamentals Buffering Output to the Browser - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Wednesday, May 29, 2019

PHP Web Fundamentals Buffering Output to the Browser

PHP Web Fundamentals



Buffering Output to the Browser

Problem

You want to start generating output before you’re finished sending headers or cookies.

Solution

Call ob_start() at the top of your page and ob_end_flush() at the bottom. You can then intermix commands that generate output and commands that send headers. The output won’t be sent until ob_end_flush() is called:

           <?php ob_start(); ?>

           I haven't decided if I want to send a cookie yet.

           <?php setcookie('heron','great blue'); ?>

           Yes, sending that cookie was the right decision.

           <?php
           ob_end_flush();

Discussion

You can pass ob_start() the name of a callback function to process the output buffer with that function. This is useful for postprocessing all the content in a page, such as hiding email addresses from address-harvesting robots. For example:

           <?php
           function mangle_email($s) {
                  return preg_replace('/([^@\s]+)@([-a-z0-9]+\.)+[a-z]{2,}/is',
                                                  '<$1@...>',
                                                 $s);
           }

           ob_start('mangle_email');
           ?>

           I would not like spam sent to ronald@example.com!

           <?php
           ob_end_flush();

The mangle_email() function transforms the output to:

           I would not like spam sent to <ronald@...>!

The output_buffering configuration directive turns output buffering on for all pages:

           output_buffering = On

Similarly, output_handler sets an output buffer processing callback to be used on all pages:

           output_handler=mangle_email

Setting an output_handler automatically sets output_buffering to on.


No comments:

Post a Comment

Post Top Ad