ob_?

Hello,

I’m on my seventh week of learning PHP (no previous coding experience) and came upon this code:

[php] //create thumbnail
$width = imageSX($SourceImage);
$height = imageSY($SourceImage);
$newThumb = imagecreatetruecolor(80, 60);
//resize image to 80 x 60
$result = imagecopyresampled($newThumb, $SourceImage,
0, 0, 0, 0,
80, 60, $width, $height);
//move image to variable
ob_start();
imageJPEG($newThumb);
$thumbnail = ob_get_contents();
ob_end_clean();[/php]

QUESTION:
What exactly is ob_start() in plain english; along with it ob_get_contents() and ob_end_clean()? --In general and what it does for the specific code example above (I get the manipulating image part of the code).
How does buffering work?

Thanks in advance,
Chris

Well, it is quite simple. First, make sure you understand PHP. PHP is a SERVER-SIDE programming system. Browsers and Javascript are CLIENT-SIDE systems. So, all PHP processing is completed on the server and the output from the code is “posted” out to the client browser where other systems take over. Such as Javascript, JQuery and CSS. Why do I explain all this? Well, most beginners think PHP code stays with the rest of the page. It does not. Once PHP has completed it’s work, it is gone. It is SERVER-SIDE only!!! Remember that and it will help you a lot down the line…

Oh, to prove this, take any PHP page and when it is displayed in your browser, just RIGHT-CLICK on the page in a blank area and select VIEW-SOURCE. You will see your nice page without any PHP on it. SERVER-SIDE-ONLY…

Now, on to OBJ. While the PHP code is being parsed and executed it contains a lot of echo’s and print’s or whatever you need to do such as creating graphics or pulling data from a database. (What PHP is designed for!) All of the “output” from the PHP code is placed into the PHP OBJ. Which you can capture if needed. To capture it, you start the OBJ, have PHP send some data or code such as HTML or JS or data form the DB and then you close the OBJ. In this way you can capture the OUTPUT that is actually sent to the browser. Then, you can save that OBJ into a variable for future use, save it to a database, write it to a file or whatever you would like to do with it. Some uses of this are creating a web page with data pulled from a database, displaying it in the page, but, keeping a copy of this in the database. Some programmers use it to save tables or reports by just writing the data to a file and naming the file “somereport-5-19-2012.html”. In this way, a link of this report could be posted and it could be displayed with ease as it is already a html page. Some use the OBJ to create “templates” of their pages to save with options created by the user. The uses are limitless. Sometimes it is tricky to use, but, can be a powerful tool.

Hope that explains it and sorry if it was long winded… Good luck!

Sponsor our Newsletter | Privacy Policy | Terms of Service