Home > HowTo's, PHP > Templating in PHP in 10 seconds flat

Templating in PHP in 10 seconds flat

December 6th, 2008 Leave a comment Go to comments

One of the rather messy practices that the PHP documentation actually encourages is the practice of using include or require to correctly layout a web page.

The PHP manual suggests that two pages be created: header and footer, and that these are included at the beginning and end of each document.

Thus for a ‘contact us’ page the contact.php file would look something like:

<? include("header.php") ?>
... The contact pages HTML ...
<? include("footer.php") ?>

While this does work, there are easier ways to accomplish the same thing and still maintain compatibility with editors such as Dreamweaver which seems to choke on even a small amount of PHP.

The under-documented auto_prepend_value and auto_append_values get a brief mention in the ini directives documentation but I thought it would be nice to show an example of how these can be used in the wild,

Adding the following to either an existing ‘.htaccess’ (note the starting dot) or downloading the below file will do pretty much the same as the above contact.php file example did only without needing to specify the files in the beginning and ends of each separate file.

?Download .htaccess
php_value auto_prepend_file "header.php"
php_value auto_append_file "footer.php"

And as with all .htaccess directives you can override these on a directory basis. So if you need a different header and footer when inside the ‘invoices’ directory dump another copy of the above into that directory changing it as needed.

And yes this method can be merged with the previous post to work with the URL prettifier.

Categories: HowTo's, PHP Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.