20.4. How to include PHP/HTML files in a PHP-Nuke block

Suppose you want to write a block, block-bar.php, that includes the file foo/bar.php. The way PHP-Nuke displays a block is that it first includes the block, with a statement like

include("blocks/block-bar.php");

then makes a table and puts in the title, and makes another table row, and "echo"es the $content variable. Thus, the $content variable must contain all the output of foo/bar.php, if your block has to contain its output. The PHP output control functions come in here very handy. The PHP output control functions allow you to control when output is sent from the script. This can be useful in various situations, especially if you need to send headers to the browser after your script has began outputting data. The output control functions (or output buffering functions, as they are often called and as the ob_ prefix in their name suggests) do not affect headers sent using header() or setcookie(), only functions such as echo() and data between blocks of PHP code.

Output buffering is a powerful tool in PHP which allows you to buffer a script's output. You can even edit this buffer before returning it to the client. The PHP functions that constitute the output buffering toolbox are:

How can we use output buffering to include the output of foo/bar.php in our PHP-Nuke block? The idea is simple: rather than having PHP send output directly to the standard output device (the browser) as the script gets executed, we will define a special output buffer which stores all the output generated by the script during its lifetime. When we do this, the output of the script is never seen by the user unless we explicitly make the contents of this buffer visible via a call to PHP's output control API (through one of the above functions). We put the foo folder in the main phpnuke directory, and use this code our block:

ob_start(); 
include("foo/bar.php");
$output = ob_get_contents();
ob_end_clean(); 
$content = $output;

This way the $content variable will contain the output of foo/bar.php, which will thus be shown in the block. To learn more about PHP output buffering, see Output Buffering with PHP and PHP Output Buffering tutorial. See also Scripting a new Block Problem, for a complete example of including a PHP scoring application in a PHP-Nuke block.