PHP Header Include – Saving development time

I have had the opportunity to go through a lot of other developers coding skills and practices in the past few months and I must admit there is a lot of time wasting going on. Are you the type of developer that has a <title>, <meta>, <link> and <body> tag on every page without a global include? If so, let me show you how to simplify your life.

I have had the opportunity to go through a lot of other developers coding skills and practices in the past few months and I must admit there is a lot of time wasting going on. Are you the type of developer that has a <title>, <meta>, <link> and <body> tag on every page without a global include? If so, let me show you how to simplify your life.

By having a global header include you can set all your title tags in one central location as well as control which page gets what header information all in one file.

Firstly, create a file called header.php and use the below template:

header.php

<?php
	// Get the filename of the current page;
	$cpage = substr(strrchr($_SERVER['PHP_SELF'], "/"), 1);
 
	// set this to a "default" title as a backup incase you forget to mention a page. This stops it from returning nothing.
	$wtitle = "My Default Website Title";
 
	// Control page titles
	switch ($cpage) {
		case "index.php": $wtitle = "Home page title"; break;
		case "contact_us.php": $wtitle = "Contact us"; break;
		case "products.php": $wtitle = "Products Page"; break;
		case "about_us.php": $wtitle = "About us"; break;
	}
 
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head>
  	<title><?php echo $wtitle; ?></title>
  	<meta name="robots" content="index,follow,all" />
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 
	<link rel="stylesheet" href="css/style.css" type="text/css" />
	<?php
		// if you're on the products page, load the products.css file.
		if ($cpage == "products.php") { echo '<link rel="stylesheet" href="css/products.css" type="text/css" />'; }
	?>
</head>
 
 
<body>
 
 
<div id="wrapper">

Now you can start creating all your other pages and simply include the header.php file right at the top as follows:

index.php / contact_us.php / products.php / about_us.php

<?php include "header.php"; ?>
 
<div id="content">
<p>Content goes here</p>
</div>
 
<?php include "footer.php"; ?>

As you can see we have taken this one step further and also created a footer.php file. This comes in very handy when you need to put tracking code at the bottom of ever page. Instead of pasting it on every single file, simply paste it into the footer.php.

footer.php

</div>
 
</body>
</html>

I hope you find this as valuable as I do. If you do it differently please give us the details. After all, we all learn from each other.