Home arrow PHP arrow Page 3 - Output Buffering

Code Explained - PHP

Output control (or output buffering) allows you to write and execute your scripts normally but send data to the web browser at selected times. The main benefit of this system is that you can call the header(), setcookie() and session_start() functions at any place in your scripts without having to worry about the "headers already sent" error message.

  1. Output Buffering
  2. Login Script
  3. Code Explained
  4. Further suggestions
By: David Web
Rating: starstarstarstarstar / 4
September 02, 2008

print this article



Notice that Iíve highlighted the functions that are used for output buffering. To begin output buffering, we use the ob_start() function, which is located at the very top of the page:




//someone registered?


$reg="Your details have been added, please login";




//has form been submitted


//check that the username and password is not empty

if( empty($_POST['uname']) && (empty($_POST['upass']))){

print "Please enter your username and password.";

$errmsg="Please enter your username and password.";

Once youíve called the ob_start() function, every single output for this page will be sent to a memory buffer rather than to the web browser. HTTP calls, like the header() and setcookie(), won't be buffered and will operate as usual.

Towards the end of the script you will notice the ob_end_flush() function:



<td><input type="submit" name="submit" value="Login"></td>




<!-- InstanceEndEditable --></td>



<td class="copy">&copy;2008</td>




<!-- InstanceEnd --></html>

<? ob_end_flush(); ?>

This function will take the accumulated buffer and send it to the web browser. You can also use the ob_end_clean() function; it does the same thing. Both of the functions turn off output buffering.

From a developerís point of view, there is not so much of a benefit except that once you start using these functions, you really donít have to spend any time worrying about HTTP headers. When you use templates in your applications, it would be beneficial to place these functions at the top (ob_start() and ob_end_flush() at the bottom). That way, these functions will be available on every page of your site.

>>> More PHP Articles          >>> More By David Web

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: