Ridiculously simple PHP templates

Sometimes you need to make a small web site with a uniform look (and a little more flair than this site,) but installing a CMS or a templating framework seems like an overkill. Enter the ridiculously simple PHP template. It is so simple, I'll let the code speak for itself. (I hereby release it into Public Domain, by the way)

<?php
// The path to the template is given in the 'file' query parameter
$file='index.tpl';
if($_GET['file']) {
	// Add a template suffix
	$file = $_GET['file'] . '.tpl';
	if(preg_match('/^\w+$/', $_GET['file'])==false ||
		file_exists($file)==false) {
		header("HTTP/1.0 404 Not Found");
		exit;
	}
}
// Ok, we have a template.
header("Content-type: text/html;charset=UTF-8");
?>
<html>
<head>
<php
// Include a head fragment if it exists
if(file_exists($file . ".head")) {
    include($file . ".head");
}
// If no title was set (in the head fragment), generate it from the current file name
if($title == null) {
    $slash = strrchr($_GET['file'], '/');
    $title = ucwords(substr($_GET['file'], $slash < 0 ? 0 : $slash));
}
echo "<title>My page" . ($title ? " - " . $title : "") . "</title>";
?>
</head>
<body>
<-- Header text goes here -->
<?php include($file) ?>
<-- Footer text goes here -->
<<body>

And that's it! Just put the above code (suitably personalized of course) into index.php and you can access your templates (which are just regular HTML/PHP pages) like this: http://example.org/index.php?file=mypage. But wait! That's not very user friendly. To make your URLs pretty, put the following in your .htaccess file:

RewriteEngine on
RewriteRule ^([^.]+?)(?:\.html|/)?$ /index.php?file=$1

If you encounter the error Negotiation: discovered file(s) matching request... add Options -MultiViews to the htaccess file.

The above rule takes all URLs that end with .html, /, or anything else as long as the filename doesn't contain a dot. This is so we don't capture requests for images and other media. The request is redirected to our little templating script with the original path in the file paramter. Now you can instead go to http://example.org/mypage/ or even http://example.org/mypage.html

And that's all it takes to create a super easy lazy-man's templating engine.