PHP: clean up your includes!

If you’ve ever worked on any kind of PHP framework, you’ll likely know the pain that a misplaced ‘space’ in one of your includes can cause.  For the rest of you imagine this scenario:

To load a page in my framework, I have an index.php that loads in a ‘core.php’ (which isn’t web accessible for security purposes) which itself then loads in a long (20 or so) list of included files which make up my framework.  So, my core.php might look like this:

require_once("database.php");
require_once("mail.php");
require_once("something_else.php");
etc
etc
require_once("page_loader.php");
send_headers();
load_page($page_id);
send_footers();

which is lovely, keeps all the functionality of the framework nice and segregated.  However, if one of those included files actually outputs anything to the screen, it can cause all sorts of issues, especially if our ‘send_headers’ function is sending our actual HTML headers…. in this case, anything output to the screen before our HTML headers are sent can really cock things up. Even worse, trying to track down where the output is coming from can be a nightmare when you have a large number of included files.

After a bit of thinking I stumbled across the (probably) blindingly obvious way round this without spending hours debugging and trying to track down which included file is the culprit:

good old fashioned output buffering!

by doing this:

// start buffering
ob_start();

require_once("database.php");
require_once("mail.php");
require_once("something_else.php");
etc
etc
require_once("page_loader.php");

//stop buffering, discard buffer contents
ob_end_clean();

send_headers();
load_page($page_id);
send_footers();

we ensure that anything output by the included files is buffered, then discarded before we actually start outputting stuff.

lovely.




No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *