Easy-Peasy PHP

Easy-peasy PHP

Got something to say?

Share your comments on this topic with other web professionals

In: Articles

By Jim Amos

Published on March 9, 2005

One of the greatest attractions of PHP is just how easy it is to pick up the basics. Comparatively, it can be quite difficult to begin learning some of the other languages (such as JSP, ColdFusion, or ASP) used for similar purposes. For anyone who, like me, doesn’t have a background in hardcore programming, PHP is probably the ideal introduction to all that cryptic back-end malarkey. So while I am no PHP expert, the purpose of this article is to introduce a few simple techniques that Web developers new to server-side scripting should be able to learn and adapt for their own uses without too much hair pulling.

To demonstrate how just a little dash of PHP can make life easier for developers, I’ll take you through the steps of creating a very basic Web page with some dynamic content. You’ll then be able to extend the code to any project you want with relative ease.

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

<title>Simple PHP page</title>

Includes to the rescue

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.

To include a basic header in our HTML document, we’ll add the following code directly after the <body> tag:

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

All this does is tell the server to fetch the file header.php and display it in the page, embedded 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 (many do, but check with your hosting provider if you have trouble testing).

Next, we’ll add a footer element:

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

Next, create footer.php by typing the following in a new file:

<p>© 2005 Joe Blogs. All rights reserved.</p>

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.

Introducing switch conditionals

Among other things, PHP switch conditionals allow users to toggle the display of dynamic content based on selections they make.

There are other ways of achieving the same effect, most notably a myriad of Enhancing Structural Markup with JavaScript methods, but these can take more time to maintain and require processing at the client end—often a deciding factor.

I find JavaScript methods like the one in the Sitepoint example to be more complicated PHP methods. And PHP runs on the server instead of the client computer, so your site will function properly even for users who have JavaScript disabled.

Switch conditionals are set up as a list of instructions to the server to perform a basic function—in this case to display some HTML content that will change based on what is selected. The server is instructed to check whether an instance of a conditional is occurring (case). If it is, it will stop (break;) and perform the required action. In this case that means to include a file and go no further along the list. Otherwise, it will continue to the next instruction until it finds the specified condition (or returns an error because you forgot to add it!)

If that sounds like a load of garbled nonsense, don’t worry. Once you look at the script and test it, you’ll see what’s happening.

In your editor, add the following to main.php directly beneath where you placed the code for including header.php:

<?php switch($id)
case ’intro’:
include ’intro.php’;
case ’bluetruck’:
include ’bluetruck.php’;
case ’redhouse’:
include ’redhouse.php’;
case ’brownbear’:
include ’brownbear.php’;
require ’intro.php’;

What we’re doing here is telling the server, in human terms:

  1. If the user selects the option called “bluetruck,” display the included file called bluetruck.php
  2. If the user selects the option called “redhouse,” display the included file called redhouse.php
  3. If the user selects the option called “brownbear,” display the included file called brownbear.php
  4. When the user first comes to main.php, display the default file, which is called “intro.php”

Again, just like the include files we added before, we need to actually create these files before they can be called.

Here is the code for each of our Sesame Street–style content includes. Place the following code into four separate PHP files.

For bluetruck.php:

<p>The truck is painted blue.</p>

For redhouse.php:

<p>The house is red</p>

For brownbear.php:

<p>The bear is brown (how stereotypical)</p>

For intro.php:

<p>This is a simple demonstration of PHP includes and switch conditionals</p>

You might also want to add something like “Have a nice day!”, or “There will be no whitewash at the White House,” or even “Uno, dos, tres, catorce?” depending on your mood—the decision is yours.

OK, don’t upload anything yet. We are still missing a vital ingredient. How the heck do our humble users actually go about changing what content is displayed now that we have four different files to choose from?

A simple navigation list

Now we need to add some navigation controls so that the user can select which file is displayed. For now we’ll use a very basic unordered list, which you can style any way you fancy with CSS.

Create a new PHP file, then add the following link list and save it as navigation.php:

<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>

Later on we might want to use PHP to make the list highlight the current page, perhaps using Keeping Navigation Current With PHP or a similar technique. For this reason, instead of adding a single instance of navigation.php to main.php we’ll actually want to include navigation.php in each of the files (intro.php, bluetruck.php, redhouse.php, and brownbear.php). We’ll add the navigation list to all four files using PHP include code the same way as before:

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

Upload everything to your Web server and try out the links. By default the page should display intro.php. When you click on “Blue truck” the page should change to read “The truck was painted blue.”

Here’s all the above code in action.

You can use these basic PHP methods to create a simple, effective dynamic site. For something much tastier, add some CSS styles and background images, bake for 60 minutes until it looks something like this.

As this demo shows, you can even have switch conditionals in more than one place on the page. In the above example I have two sets of conditionals—one for the text and another for images. The second set of conditionals also uses the PHP print function to actually write the images and their corresponding titles to the page.

The code for the second set of conditionals is written like this:

<?php switch($id)
case ’intro’:
print ("<img src="images/intro.jpg" alt="Image of a keyboard" /><br /><h2>Intro Image</h2>");
case ’bluetruck’:
print ("<img src="images/bluetruck.jpg" alt="Image of a blue truck" /><br /><h2>Blue Truck</h2>");
case ’redhouse’:
print ("<img src="images/redhouse.jpg" alt="Image of a red house" /><br /><h2>Red House</h2>");
case ’brownbear’:
print ("<img src="images/brownbear.jpg" alt="Image of a brown bear" /><br /><h2>Brown bear</h2>");
print ("<img src="images/intro.jpg" alt="Image of a keyboard" /><br /><h2>Intro image</h2>");

This is the real appeal of PHP. We can begin with something quite basic, then add extra layers of functionality later on as we learn more about the language. In my opinion, compared to VBS Script or JSP, the learning curve is not intimidating.

Need for speed

Another powerful advantage of using PHP is that you can compress your files so that they take up less room on your server. There are multiple ways of achieving this, but the code I have had the most success with is:


Just add that to the very beginning of main.php. Right now the file is very small anyway, but in a real-world situation it would contain much more code. You’ll soon see the speed benefits of this simple file compression method.

You can import your CSS as a PHP file. This offers you a range of options for creating CSS on the fly using arrays and variables and means you can compress your style rules too. Just add this PHP header to the beginning of your CSS:

ob_start ("ob_gzhandler");
header("Content-type: text/css");
header("Cache-Control: must-revalidate");
$offset = 60 * 60 ;
$ExpStr = "Expires: " .
gmdate("D, d M Y H:i:s",
time() + $offset) . " GMT";

Remember to save your CSS file with the PHP extension and import it properly.

And that’s a wrap for now. This is just scratching the surface of what’s possible with PHP, but hopefully we’ll see many more articles on this subject soon. If you’ve never written any PHP before, I hope this article has been a useful introduction to some very handy techniques.

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.