Output control, you say? What's that? And more importantly, why do I care? As the name suggests, PHP's output control functions provide a way for you, the developer, to exercise some degree of control over how the output generated by a particular PHP script is handled. Why do you need this? Perhaps the best way to demonstrate is with an example. Here's what you'll see when you browse to the script: In this case, PHP barfs because I've attempted to send a HTTP header to the browser after the script has generated a line of output. If you know anything about HTTP, you know that this is a big no-no - as the PHP manual succinctly puts it, "...you can not normally send headers to the browser after data has already been sent...". So where does that leave you? Well, either you make it a point to ensure that all sensitive code - like the code that generates HTTP headers - always appears right at the top of your scripts...or you get creative with the output control functions available to you in PHP. Now, if you run this script, you'll see the output with no nasty error messages spoiling the view. How did this happen? Well, it's fairly simple. In this case, rather than having PHP send output directly to the standard output device (the browser) as the script gets executed, I've chosen to define a special output buffer which stores all the output generated by the script during its lifetime. When I do this, the output of the script is never seen by the user unless I explicitly make the contents of this buffer visible via a call to PHP's output control API (discussed in detail on the next page). When you compare the two examples above, the advantage of using this technique should immediately become clear. By using a memory buffer to manage how the output of my script appears, I can do things which would otherwise be difficult or tedious - including sending HTTP headers to the browser *after* a script has started generating output, or (as you will see) displaying different Web pages on the basis of conditional tests within my script.
blog comments powered by Disqus |