Using the PHP Include Function to Template Faster

Today’s tutorial shows how using PHP’s include function for common elements can speed up development time. We’ll go over basic implementation and how to display page specific information (e.g. current menu location) while still using the common file.

Even if you’re the type of designer that outsources anything past XHTML/CSS, you’ll want to read this. Using includes in your next design can drastically cut down maintenance and time spent updating pages. This is PHP for designers at its finest.

How does include() work?

Put simply, the include function allows multiple pages to load the same blocks of code or common elements. This makes maintaining larger sites easy, because you’re able to make changes in one place and have those results effect everything at once. Nobody wants to go through dozens of pages just to update one menu item.

Includes work by taking chunks of code, and rendering it as part of the page. Think of it like reusable puzzle pieces.

Cutting Down the Common Code

As you can imagine, an enormous amount of repeat code is spared when duplicate pieces are put in the same place. Pages with thousands of lines may be reduced to a couple hundred. Scanning code couldn’t be easier. A page’s source code might look something like this before includes:

<!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" xml:lang="en" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<title>PHP Include Demo</title>
	<link rel="stylesheet" href="styles/global.css" type="text/css" />
</head>
<body>
	<div id="wrapper">
               <div id="header">
	             <ul id="navigation">
		          <li class="home"><a href="index.php">Home</a></li>
		          <li class="about"><a href="about.php">About</a></li>
		          <li class="services"><a href="#">Services</a></li>
		          <li class="contact"><a href="#">Contact</a></li>
                     </ul>
		</div>

		<div id="content">
			<h1>Welcome</h1>
			<p>What a wonderfully constructed sentence!</p>
		</div>

	</div>

</body>
</html>

…and something like this after:

<?php include_once('./includes/header.php'); ?>

		<div id="content">
			<h1>Welcome</h1>
			<p>What a wonderfully constructed sentence!</p>
		</div>

<?php include_once('./includes/footer.php'); ?>

As you can see in the code above, all common code for pages have moved to the header.php and footer.php files. This makes editing much simpler, because the only page-specific code is visible.

For successful includes in templates, you will need to change certain pieces inside the included files from page to page. In the next step, we’ll take a look at how to pass variables into the referenced file.

But pages are dynamic!

It’s easy to convert an existing HTML template to include statements. The hard part comes when there are special cases.

If you’re already familiar with the include function, you may have run into a problem when trying to change information contained in the common elements (e.g. the page title) for specific pages. Not all information contained in the common files is the same for each page. Especially with navigation involved, these common elements still needs the ability to change.

Define Page Information

To keep things simple, we’ll stick with two unique elements for each page:

  1. Change the page title
  2. Highlight the current location on main menu

Both of these changes are controlled through variables defined on the each page. These will then carry over to the final page render. In order to do this, we’ll need to declare the variables before loading the header include. This lets us have a dynamic include of common code, instead of being stuck with the defaults.

Let’s go back to our earlier example and add in some extra variables. Keep in mind that this should appear at the top of the page file, and above any of the page’s content.

<?php
	//Set values for page
	$page_title = "Home | PHP Include Demo";
	$current_page = "home";

	//Load header
	include_once('./includes/header.php');
?>

<!-- Page's HTML and content starts here -->

Display the Results

Once you’ve defined the title and current page variables, header.php will now be able to pull the information when loaded. Below are two sample code snippets to display page title and highlight the current menu location.

Page Title

<title><?php echo $page_title; ?></title>

Current Menu Location

This is probably one of the most common conflicts involving includes. Using the code below with the passed variable, the current menu location is assigned a class of “selected”. Some simple CSS styles can take it from there.

<ul id="navigation">
	<li class="home"><a <?php if ($current_page == "home") { ?>class="selected"<?php } ?> href="index.php">Home</a></li>
	<li class="about"><a <?php if ($current_page == "about") { ?>class="selected"<?php } ?> href="about.php">About</a></li>
	<li class="services"><a <?php if ($current_page == "services") { ?>class="selected"<?php } ?> href="#">Services</a></li>
	<li class="contact"><a <?php if ($current_page == "contact") { ?>class="selected"<?php } ?> href="#">Contact</a></li>
</ul>

Includes in Action

Now that your pages have a sort of “dynamic” includes, you’ll be able to easily customize results. I’ve taken a screenshot of an example page for reference. Source code for this project can be downloaded below.

Make things much easier to scale, doesn’t it?

Closing Thoughts

This kind of strategy is old news to all the PHP veterans out there, but it’s also a great tool for designers. There’s no limit to the number of elements that you can control from page to page — experiment away! I’ve included the source code of a similar project to help get you started.

If any PHP experts out there have suggestions or tips for best practice, we’d love hear from you. As always, please leave any questions or thoughts in the comments below.

  • Stumble It!
  • Bookmark It!
  • Tweet it!

About Zach Dunn

Zach is a partner and interface designer at One Mighty Roar from Massachusetts, USA. Follow him on Twitter @zachdunn.

 

Discussion

  1. Eric B.

    December 3rd, 2009 at 1:31 AM

    These are some very useful tips. They will be very helpful, especially for beginners to PHP.

  2. twe4ked

    December 3rd, 2009 at 1:59 AM

    Worked all this out the hard way years ago, great to finaly see it all in one place in an easy to understand manner, I will be pointing people here in the future :)

  3. Design Informer

    December 3rd, 2009 at 4:23 AM

    Thanks guys. This will make coding those big sites with lots of pages very easy. Sometimes, you don’t need a CMS but you do need PHP functions like these.

  4. Benjamin Reid

    December 3rd, 2009 at 5:44 AM

    A pretty basic usage of PHP but it’s well explained for beginners. It’s nice to turn

    if ($current_page == “home”) { … }

    into a function, so you could put

    if(is_page(‘home’) { … }

    similar to WP. I posted an example a while back: http://bit.ly/7qlbxO

  5. Jônatan Fróes

    December 3rd, 2009 at 6:00 AM

    @Benjamin Reid functions are slower the “ifs”
    I’d create an array and make a foreach with some if…
    —–
    Great tips. Very useful.

  6. Edmundo Junior

    December 3rd, 2009 at 6:15 AM

    Best tutorial ever! I’ve been looking for this for a long time, thanks man!

  7. Fritsie

    December 3rd, 2009 at 6:49 AM

    Good tutorial, well explained.

    One question though. You explain how to dynamically change the page title, but how to change the url of the page. For instance, when viewing the about page the url would spell http://www.domain.com/about instead of http://www.domain.com. This would benefit SEO as far as I understand.

    Or is this beyond the scope of the article?

  8. deb

    December 3rd, 2009 at 6:53 AM

    Thanks for writing this Zach, perfect timing.

    Could you please also write some basic MySQL intro tutorials, like how to save info into database and retrive to use in pages. Just some basic example.

    Such types of tuts will be really helpful for people like me who are neither pure designers nor experienced php devs, mostly limited to static frontend coding.

  9. daveStorybook

    December 3rd, 2009 at 8:00 AM

    @fritsle, I may be wrong here as I am completely new to php but I don’t think you need to dynamically change the urls. index.php, about.php etc are still seperate files. Clever people please correct me if I’m wrong

  10. Timothy

    December 3rd, 2009 at 8:31 AM

    Just be careful in your navigation anchors. I usually set up a variable in a global include that has a relative path, like ” or ‘../’ or ‘../../../’ etc

  11. Zach Dunn

    December 3rd, 2009 at 8:45 AM

    @fritsie

    The intention of this tutorial was to show how you can substitute page information into the included files at load time. What you’ve described sounds like a dynamic job for PHP with AJAX. Sorry for the confusion!

  12. Matt

    December 3rd, 2009 at 9:42 AM

    I remember when I first learned about php includes, it was a revelation. It’s great to see an article like this that explains how to do it in such a simple and clear way.

    @fritsie
    What you’re referring to is url rewriting and is definitely beyond the scope of this article. If you want to find out more about it just do a quick search for ‘mod_rewrite tutorials’.

  13. Jess

    December 3rd, 2009 at 10:01 AM

    Great post. I’ve been using common include files for a few years, but have never really gone beyond that. Knowing how to use dynamic include files will really help. Thanks!

  14. Jorgen

    December 3rd, 2009 at 10:15 AM

    I’d recommend using the alternative syntax for templates (Wordpress style). This makes it easier to read your code and gives more seperation between ‘normal’ PHP files and template files.
    <a class=”selected” href=”index.php”>Home

    Also PHP has two functions, Include and Require, the difference being that Require throws a fatal error when something goes wrong and PHP stops al toghether, which could lead to only half a page shown. Include throws a warning, usually displaying a message on the screen but the rest of the script is still executed.

  15. Brian Muse

    December 3rd, 2009 at 10:18 AM

    @Fritsie

    mod_rewrite with apache and .htaccess is pretty straight forward if you google some tutorials. You’ve got to be pretty well versed in regular expressions to do most anything with it, though.

    However, if what you’re suggesting is bootstrapping with a single index.php file and templating from there, it’s fairly simple. Just include the following in your .htaccess:

    RewriteEngine on
    RewriteBase /
    RewriteRule !\.(js|ico|txt|gif|jpg|png|css)$ index.php

    This will load run index.php on your server regardless of what subdirectories and files are in the URL.

    If this is what you thought the article intended, however, you’ve misunderstood.

  16. sandeep

    December 3rd, 2009 at 1:15 PM

    i a php programmer , and i am using this methode last 4 years so this is not a new one sorry

  17. Tommy

    December 3rd, 2009 at 1:26 PM

    @sandeep

    You might want to read the article again, I see no where this was described as a new technique.

  18. Pep

    December 3rd, 2009 at 1:36 PM

    Thanks a lot ! I was looking for such a simple and clear explanation of basic php a long time ago.

    I agree with deb, a tutorial like this one about MySQL would be great !

  19. Andrew Champ

    December 3rd, 2009 at 1:38 PM

    Remember to name your external include file with the extension .inc, not .php. You’ll get an error using php in a .php include. Confused, lol.

  20. Fritsie

    December 3rd, 2009 at 2:24 PM

    @all who responded to my question

    I kinda figured it was beyond the scope of the article but it was worth a try. I’ll google for mod_rewrite because that’s what I’m aiming for here I guess. Perhaps Zach could do a tut on that some day? Wouldn’t be a misfit on this blog. :)

    Thanks guys!

  21. avanzaweb

    December 3rd, 2009 at 2:25 PM

    Almost the same things I do, except the navigation

  22. Shawn B.

    December 3rd, 2009 at 3:03 PM

    @deb MySQL is really lame and is really no fun for anyone. There are so many ways to make it more fun by bossing it around with PHP, Ruby on Rails, or like 1000 other languages but the diversity of options can make it hard to find a general tutorial.

    My suggestion is to do some research into frameworks and pick one that really works for you then see how they do it. Picking a framework that uses a Model View Controller system is probably a good idea too since that is really where everything seems to be going and once you figure it out a lot of the concepts carry over.

    To learn more about frameworks I suggest this article:
    http://buildinternet.com/2009/08/why-php-frameworks-matter/

    Also you might want to read up on SQLite:
    http://buildinternet.com/2009/10/easy-databasing-with-sqlite/

  23. Lover of Sadness

    December 3rd, 2009 at 3:57 PM

    i believe there isnt a single php programmer who doesnt know this… this is one of the very basic of PHP

  24. Greg

    December 3rd, 2009 at 4:32 PM

    Oy vey…

    Sandeep (and even worse, Lover of Sadness, who commented after Sandeep had been replied to)… it says specifically in the article that this is not for PHP developers, but for HTML/CSS developers who might not know how easy basic PHP can be, and would otherwise outsource it.

    Thanks for the article, Zach, I did indeed already know about the technique, but the explanation of your approach to the navigation menu will already be helpful to a legacy site I inherited that was accomplishing a similar task in a much more complicated way. Good stuff!

    The small extra point I would add in the spirit of helping the beginners is that the main page doing the include must typically have the extension “.php” in order for the web server to parse it for PHP code.

    BUT, as far as I know, the additional pages do not “need” to have the .php extension… this is already covered by the page doing the includes.

    index.php which includes header.html and footer.html should still allow for parsing of PHP inside the two .html pages.

    But the main point is… the page doing the initial PHP should have the .php extension, if that wasn’t already obvious/clear.

  25. Austin

    December 3rd, 2009 at 5:01 PM

    @Jônatan

    Functions aren’t that much slower than using conditional statements… we are talking a different of a millisecond or less.

    Also, your solution with loops and conditionals may even take longer.

  26. Manmada Reddy

    December 3rd, 2009 at 11:06 PM

    @Andrew Champ
    We can use .php also as a include in other php files.
    Some people will use .inc, .html as per their convince.
    If we are using .inc, then we will have a chance to restrict the users not to access only include parts.
    I mean, If we are using .php/.html, users can access “http://www.site.com/header.php” or “http://www.site.com/footer.php” directly.
    If we are using “.inc” file, then we can set server configuration to deny the direct access to .inc files.

    order deny,allow
    deny from all

    @Greg
    Extension of the file can be configured at server level.It is not restricted to only .php
    In server configuration, we can set different allowed type of file extensions for php.
    Configuration looks something like this.
    AddType application/x-httpd-php .php .php3 .php4 .html

    The above configuration says that please pass all .php,.php3,.php4,.html extension files php engine for parsing.

  27. Blogger Den

    December 4th, 2009 at 2:38 AM

    Wow, really great article! I have found using PHP includes is the best way to build a complicated site, and it allows for very large expandibility

  28. Kerrin English

    December 4th, 2009 at 3:37 AM

    The only problem with this method is if you are calling the include function on a page that is inside a subfolder then the include won’t work as it will be trying to reference the file in the local directory.

    Eg. http://www.yoursite.com/subfolder/article1.php

    In this case the include will try and find the file at this location:

    http://www.yoursite.com/subfolder/includes/header.php

    The most straightforward method to solve this is to always use absolute paths.

    Eg. include_once($_SERVER['DOCUMENT_ROOT'].’/includes/header.php’);

    It’s important to note if anyone wants to do a similar thing with including css files or Javascript files for example, you will have to use ($_SERVER['HTTP_HOST']), or simply type out the exact http path (http://www.yoursite.com/mysitescss.css). This is because php uses server file paths, whereas css, javascript etc. are basically included using a url.

  29. Rory

    December 4th, 2009 at 4:54 AM

    good tutorial on the useful basics of php includes, however including the head object makes it awkward to add javascript (especially if it is something specific to a single page).

    I usually manually include the basic html structure but include the site header (logo image etc) and the site footer (copyright info, adress details, links etc) along with a similar method for navigation, however I keep my navigation referenced numerically, soo instead of $current_page = ‘home’; I use $current_page = 1;

    This is especially useful when you have pages called machinery_business_assets.php keeps the code a lot shorter.

  30. web developer indonesia

    December 4th, 2009 at 5:57 AM

    Thanks. Great post for newbie.

  31. Brian Muse

    December 4th, 2009 at 7:25 AM

    @Rory
    This tutorial was just covering the basics, but if anyone were to delve even just a little deeper into all this they’d realize many solutions to dynamically including different javascript.

    For example you could do it like Codeigniter does and preset some $data['extraHeader'] variables to be output in the header.php file.

    Additionally you could define a function called includeHead() in you main file that outputs additional header html and have that called in your header file.

    Numerous solutions for this.

  32. Eric Beringer

    December 4th, 2009 at 9:26 AM

    Just to clarify, like PHP echo, include is not a function, but a language construct. There is no need to add parenthesis when including a file. Subsequently, the require and require_once constructs are not functions either.

  33. Kevin May

    December 4th, 2009 at 11:12 AM

    Don’t forget that you can also add an “else” to those nav links like this….

    <a class=”portfolioselected” href=”portfolio.php” class=”portfolio”>Portfolio

    That is if you don’t use a class on the “li”, but have it on the “a”, like me ;)

  34. Kevin May

    December 4th, 2009 at 11:14 AM

    Opps that didn’t work.. oh well

  35. Web, Graphic, Blog Design | BrandleDesign

    December 4th, 2009 at 1:34 PM

    Some great advice. Thanks for sharing Zach.

  36. Daniel

    December 4th, 2009 at 6:23 PM

    PHP included’s is very basic but is very very useful when building larger site’s & app’s.

    Great tutorial, great for beginners….

  37. ThinkSoJoE

    December 5th, 2009 at 12:37 AM

    You know, I never thought of passing the page title before including the header. I’d been using a function that pulls it from the database, and I’d imagine that using this method instead would reduce load on the server and speed up the load times on my site. Thanks for this post!

  38. Jack Starr

    December 5th, 2009 at 4:45 AM

    Im using codeigniter as my web machine, and i use template parse.

  39. novi

    December 10th, 2009 at 1:23 AM

    it’s highly informative and clearly explanation…
    finally i’ve found tutorial to do my assignment..
    thanks for this post :)
    and visit me at toko online

  40. teebee

    December 10th, 2009 at 4:57 PM

    @fritsie

    Here’s a couple links to pages I’ve collected that may be of interest to you (and maybe to others).

    http://www.noupe.com/php/htaccess-techniques.html
    http://net.tutsplus.com/tutorials/other/a-deeper-look-at-mod_rewrite-for-apache/

  41. Jim Mayes

    December 12th, 2009 at 7:58 PM

    instead of using php if statements in the nav to apply a style, why not just stick to css? If you use a class or id on the body tag the cascade can take care of applying the style.

    So for instance you have a nav that is simply (remove the php)

    Home
    About

    Then give each page a class in the body tag that corresponds to the nav links, like so

    then you just need a css rule with the correct selectors for each combination, like this

    body.home #navigation li.home,
    body.about #navigation li.about {
    /* you selected state styles go here */
    }

    there’s no real need to use php to accomplish styling a selected page when css can do it very easily

  42. Jim Mayes

    December 12th, 2009 at 8:07 PM

    sry, your comment form cleaned out my html, that sample code should look like this:

    <ul id=”navigation”>
    <li class=”home”><a href=”index.php”>Home</a></li>
    <li class=”about”><a href=”about.php”>About</a></li>
    <li class=”services”><a href=”#”>Services</a></li>
    <li class=”contact”><a href=”#”>Contact</a></li>
    </ul>

    <body class=”about”>

    body.home #navigation li.home,
    body.about #navigation li.about {
    /* you selected state styles go here */
    }

  43. Greg

    December 15th, 2009 at 10:59 AM

    @Manmada: I had typed in something to that effect but didn’t submit. I figured if this article is meant more for beginners I didn’t want to throw them off. But I will also admit, I usually hand off the mucking around in web server config to other folks, so I didn’t know the actual syntax offhand; save myself the embarrassment by not even trying. ;-) Thanks for providing that for us!

    As I’m sure you already know (I’m just mentioning it for other readers) telling the server to parse .html for PHP is going to add some extra load. Not a problem for small sites, but the savings of cycles can add up when it’s a high-traffic web app. I’d be curious to see the metrics, but alas I don’t have them. Suffice it to say, even without concrete metrics it is considered good practice to not parse .html for .php.

    @Jim: I get what you’re doing, but I’m not sure I prefer it to the PHP approach. I’ll give it a go for experimentation’s sake, though. Thinking outside the box ftw!

  44. Jacques

    January 3rd, 2010 at 1:24 AM

    Thank you for sharing. I’m a aspiring php developer and I would say that my skill set is definitely at novice, and this tutorial is to the point and helpful!

  45. Shantanu

    January 22nd, 2010 at 4:57 PM

    Bloody brilliant!
    This has helped me learn a templating / construction system that simply makes PHP and CSS come together so beautifully.
    This makes CMS overkill for a lot of my clients, when I can simply set up CKEditor with the flat files and let them kick the flatfiles around.

    Thanks so much.
    This article is what I’ve been looking for a long time. I really learned a lot from this!

  46. Clarity

    March 17th, 2010 at 1:08 PM

    I found the bit about passing variables especially helpful since this concept can also be applied to other functions.

    Thank you :)

Join the Conversation!

Remember: Life's not all doom and gloom, so please keep it constructive. If we've made an error or missed something big, please let us know! Learning is revisions, after all.

CommentLuv is Enabled

 

Sponsors

Advertise on Build Internet!