Simple Layouts with PHP

This tutorial is for those starting out in PHP and want to learn a great way to create layouts. This will help reduce redundancy and keep you from writing too much code.

Download the Source

Anyone that has been developing HTML based sites for some time has undoubtedly ran in to the issue of keeping the design consistent across multiple pages. Most websites follow a similar layout to the picture. This is great unless you have sites that require multiple pages. What happens when that one link is changed from say “Contact Me” To “Contact Us”? Well you have to go in to each of the pages and update the code. That is slow and prone to error if you forget a page or something. So we want to employ PHP to solve that problem for us. There are actually two ways I am going to cover and at the end I’ll let you know which I prefer and why.

Technique #1


A lot of sites follow this kind of layout scheme

The first technique is the entry level solution that works across nearly all situations. It involves using the PHP include() function. Be sure to check out the documentation on this function because we will use it a lot! Basically it boils down to this you have a page and you want to include the contents of another page in it. This is not really possible in HTML without employing weird frame solutions. To visually realize the concept think about each color on the picture above as being a separate document (i.e. head.html, nav.html, footer.html). Now what does the code look like that puts it all together?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <link rel="stylesheet" href="/css/reset.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="/css/style.css" type="text/css" media="screen" />
    <script src="/js/jquery.js" type="text/javascript" charset="utf-8"></script>
  </head>
  <body>
    <div id="hd">Some Site Logo</div>
    <div id="bd"></div>
    <div id="ft">Copyright Info</div>
  </body>
</html>

Take out everything up to the point

and put that in a new file called head.php. Then take the rest of the document and put that in a file called foot.php. Make sure your head and foot files are in the same directory as the original file. Now you have a blank PHP file. Put the following code inside of it:

<?php include("head.php"); ?>
CONTENT HERE
<?php include("foot.php"); ?>

Now just put whatever HTML/PHP content you want in between those two include statements and check it out in a browser. You won’t notice a difference there because the browser doesn’t see the includes just the HTML that is spit back to it. Now if you insert the same code in a new PHP file and put different content in between the tags you can load that and you’ll see that it has the same header and footer sections but new content. This is great because now if we make one change to the head.php or foot.php files it’ll be represented across all our pages. This will greatly minimize the amount of time spent updating similar things on pages. Remember you are not limited to how many includes you have so you could have an include for a nav section and put it in either the head.php or the content PHP file.

It may be easier to think of it as a puzzle, you are piecing together a complete HTML page with includes.

Technique #2

Alright we have that under our belt let’s look at another solution. This one is kind of the inverse of the first. Above we included the common elements on each page, now we will include the different elements on a common page. Here is what it will look like in a PHP file.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <link rel="stylesheet" href="/css/reset.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="/css/style.css" type="text/css" media="screen" />
    <script src="/js/jquery.js" type="text/javascript" charset="utf-8"></script>
  </head>
  <body>
    <div id="hd">Some Site Logo</div>
    <div id="bd">
      <?php include("about.php"); ?>
    </div>
    <div id="ft">Copyright Info</div>
  </body>
</html>

This will be your index.php, but the content will change based on the links the user goes to. The only problem is that we need to have a way to change include to what page the user is wanting. This means that our page is all setup in one file and we just have snippets of code for the content of the site that we dynamically include within that base page. This leads to a new subject that we will graze over because it is so complex we should dedicate an entire article to it. In PHP there are things called global variables that you can use in your code to get information from the user. The information we will be taking is the page they want to look at.

Say this is the URL to our about page: http://domain.com/index.php?page=about

What this says in that we are accessing the file called index.php, and sending it a variable called page with the value of about. We can also include more variables by separating them with the ampersand symbol (&). Now we need to tell our PHP code to use that variable. Change the input function call to look like this:

<?php include($_GET['page'].".php"); ?>

$_GET is a special variable holder in PHP that stands for the variables sent in the URL of the current page. Anything between the two tick marks is the variable name we want the value of. Remember from above that we set page equal to “about”. The period between the $_GET and “.php” is the way to tell PHP to join the strings into one, so PHP will interpret the code as

<?php include("about.php"); ?>

This is great so now if we want to make a new page we just put content into a new file and call it something.php and now we have a consistent look across all pages and we don’t have to remember to put the include statements on each page. So a URL to our site would look like this http://domain.com?page=something

Now anyone who knows a little PHP might be screaming “INSECURE!” and they would be right, because this means we are allowing the user to include whatever file they want! For instance go to http://domain.com?page=index what do you get? Well a continuous loop of includes, yikes! Even worse they could include files that you don’t want them to for security reasons. So how do we fix this?

Well in our code we want to limit what pages can be included, think of it as a white list of okay pages. This will employ what is known as an array, or a collection of variables and the function in_array(). In_array() basically checks if a given value is in a given array. The code for this looks like

<?php
  $whitelist = array("about", "contact", "random");
  if(in_array($_GET['page'], $whitelist)) {
    include($_GET['page'].".php");
  }
?>

We are also using an if statement. Think of it as a padlock that is only open IF the stuff between the parenthesis is true. Meaning the code between the curly brackets is only executed if the IF statement is true. So if the value passed in as page is in the array $whitelist then include that page. If it isn’t we don’t do anything. This solves the problem of them including pages we don’t want them to.

Conclusion

Today we learned two really simple ways of creating centralized themes for a PHP application. My personal choice is Technique #2 because it elminates the need to write include statements on each page and gives more flexibility. For those looking for something a bit more advanced check out this tutorial on the smarty template system by Isa Hassen. I hope this will save some people a little bit of time. As always I am available in the comments or on Twitter, @noahhendrix. Happy Coding!


19

Comments
  • TheCosmonaut says:

    Good, simple article. One thing that’d be really nice to take it to the next level would be to include instructions on how to use htaccess to mask URLs to make search engine friendly URLs…

  • Johnathan Barrett says:

    I was planning on writing something pretty similar to this, the second one along with using .htaccess.

  • Yeppe am the first

  • mary says:

    Nice simple explanation for beginners :)

  • saurabh shah says:

    nice n very simple one…. and agreed with TheCosmonaut ….

  • Adam16ster says:

    great for beginners, i wish i couldve read tutorials this thorough when i was first starting out. explaining what each item in the code does goes a long way. you couldve taken the easy route explaining the concepts and that would have been good but beginners wouldnt know what to do with it. so i thank you for the extra effort and look forward to more (advanced) tuts from you.

  • BandonRandon says:

    Good for beginners the only suggestion i would have would be adding an “else” clause to the if statement above. Something like.

    This will then load the header and footer and then if there isn’t any whitlisted page alert the user of such.

    Just a though,
    Brooke

  • rbroen says:

    For starters: “I love the In the Woods” – blog.
    I work for a hosting company and often run into examples as you have given in “Technique #2″, and when I have to go find them, they are being abused big time. You do state that it is safer to use a white list, but people are going to find a complete and working example in this article and not apply your patch.
    Please add a big UNSAFE STATEMENT warning near the complete and unsafe example. Thank you.

  • Chris says:

    Like the first comment states, maybe you could do a follow up tutorial on using .htaccess to mask the url’s?

    Chris

  • Hi, Nice information on this topics. I really enjoyed it. But what do you think if some one can get an opportunity doing business at home and earn more money then a person who do the jobs. Check out http://companiesproducts.com/sembusinessblueprint.php and tell me what do you think? Thanks, for sharing this information.

  • Noah Hendrix says:

    I encourage everyone to check out this tutorial on learning to mask URLs with HTACCESS:

    http://net.tutsplus.com/tutorials/other/using-htaccess-files-for-pretty-urls/

  • PJ says:

    this is bad advice for beginners …. using $_GET unfilterd with inlcude is a really bad thing to teach people who don’t know any better.

    don’t do it

  • Mike McKee says:

    One must be careful to follow that step with the in_array() call. If you fail to do that, your site could definitely be open to XSS attacks where for instance I might do…

    ?page=../../file.txt

    …where as you can tell I can start poking around one’s hard drive on the server checking out files.

  • Basit says:

    part 2 with http://smarty.php.net for beginners..

  • Rohan says:

    Great article. Thanks!

  • Greg says:

    Nice tutorial!
    How would i go about using htaccess to shorten the filename to http://domain.com/about for example when loading about.php into index.php with the seconded technique used in this tutorial.

  • lord xeon says:

    its a good tutorial up until the second part. Even with the whitelist, it’s still a horrible idea to include anything gotten with php’s $_GET. It’s just bad coding.
    Stick with the first one, it’s simple, and it works, and it’s not hard to include two files, it’s literally 2 lines of code that you can copy and paste into each new page, you could probably make a template if you’re really lazy.

  • Benny Dacks says:

    This is just a bad idea all together. Think about the XSS/Injection implications of this unsanitary query string. Yikes…