Article

Build Your Own Database Driven Web Site using PHP & MySQL, Part 3: Introducing PHP

Page: 1 2 3 4

Hiding the Seams

You’re now armed with a working knowledge of the basic syntax of the PHP programming language. You understand that you can take any HTML web page, rename it with a .php file name extension, and inject PHP code into it to make it generate some or all of the page content on the fly. Not bad for a day’s work!

Before we go any further, however, I want to stop and cast a critical eye over the examples we’ve discussed so far. Assuming your objective is to create database driven web sites that hold up to professional standards, there are a few unsightly blemishes we need to clean up.

The techniques in the rest of this chapter will add a coat of professional polish that can set your work apart from the crowd of amateur PHP developers out there. I’ll rely on these techniques throughout the rest of this book to make sure that, no matter how simple the example, you can feel confident in the quality of the product you’re delivering.

Avoid Advertising Your Technology Choices

The examples we’ve seen so far have contained a mixture of plain HTML files (with names ending in .html), and files that contain a mixture of HTML and PHP (with names ending in .php). Although this distinction between file types may be useful to you, the developer, there is no reason your users need to be aware of which pages of your site rely on PHP code to generate them.

Furthermore, although PHP is a very strong choice of technology to build almost any database driven web site, the day may come when you want to switch from PHP to some new technology. When that day comes, do you really want all the URLs for dynamic pages on your site to become invalid as you change the file names to reflect your new language of choice?

These days, professional developers place a lot of importance on the URLs they put out into the world. In general, URLs should be as permanent as possible, so it makes no sense to embrittle them with little “advertisements” for the programming language you used to build each individual page.

An easy way to do away with the file name extensions in your URLs is to take advantage of directory indexes. When a URL points at a directory on your web server, instead of a particular file, the web server will look for a file named index.html or index.php inside that directory, and display that file in response to the request.

For example, take the today.php page that I introduced at the end of Chapter 1, Installation. Rename it from today.php to index.php. Then, instead of dropping it in the root of your web server, create a subdirectory name today, and drop the index.php file in there. Now, load http://localhost/today/ in your browser (or http://localhost:8080/today/, or similar if you need to specify a port number for your server).

The figure below shows the example with its new URL. This URL omits the unnecessary .php extension, and is shorter and more memorable—both desirable qualities when it comes to URLs today.

A more fashionable URL

Use PHP Templates

In the simple examples we’ve seen so far, inserting PHP code directly into your HTML pages has been a reasonable approach. As the amount of PHP code that goes into generating your average page grows, however, maintaining this mixture of HTML and PHP code can become unmanageable.

Particularly if you work in a team where the web designers are unsavvy, PHP-wise, having large blocks of cryptic PHP code intermingled with the HTML is a recipe for disaster. It’s far too easy for designers to accidentally modify the PHP code, causing errors they’ll be unable to fix.

A much more robust approach is to separate out the bulk of your PHP code, so that it resides in its own file, leaving the HTML largely unpolluted by PHP code.

The key to doing this is the PHP include statement. With an include statement, you can insert the contents of another file into your PHP code at the point of the statement. To show you how this works, let’s rebuild the “count to ten” for loop example we looked at earlier.

Start by creating a new directory called count10, and create a file named index.php in this directory. Open the file for editing and type in this code:

<?php    
$output = '';    
for ($count = 1; $count <= 10; ++$count)    
{    
 $output .= "$count ";    
}    
   
include 'count.html.php';    
?>

Yes, that’s the complete code for this file. It contains no HTML code whatsoever. The for loop should be familiar to you by now, but let me point out the interesting parts of this code:

$output = '';

Instead of echoing out the numbers 1 to 10, this script will add these numbers to a variable named $output. At the start of this script, therefore, we set this variable to contain an empty string.

$output .= "$count ";

This line adds each number (followed by a space) to the end of the $output variable. The .= operator you see here is a shorthand way to add a value to the end of an existing string variable, by combining the assignment and string concatenation operators into one. The longhand version of this line is $output = $output . "$count ";, but the .= operator saves you some typing.

include 'count.html.php';

This is an include statement, which instructs PHP to execute the contents of the count.html.php file at this location.

Outside of this book, you will often see includes coded with parentheses surrounding the filename, as if include were a function like date or htmlspecialchars, which is far from the case. These parentheses, when used, only serve to complicate the filename expression, and are therefore avoided in this book. The same goes for echo, another popular one-liner.

Since the final line of this file includes the count.html.php file, you should create this next:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"    
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">    
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">    
 <head>    
   <title>Counting to Ten</title>    
   <meta http-equiv="content-type"    
       content="text/html; charset=utf-8"/>    
 </head>    
 <body>    
   <p>    
     <?php echo $output; ?>    
   </p>    
 </body>    
</html>

This file is almost entirely plain HTML, except for the one line that outputs the value of the $output variable. This is the same $output variable that was created by the index.php file.

What we’ve created here is a PHP template—an HTML page with only very small snippets of PHP code that insert dynamically-generated values into an otherwise static HTML page. Rather than embedding the complex PHP code that generates those values in the page, we put the code to generate the values in a separate PHP script—index.php in this case.

Using PHP templates like this enables you to hand your templates over to HTML-savvy designers without worrying about what they might do to your PHP code. It also lets you focus on your PHP code without being distracted by the surrounding HTML code.

I like to name my PHP templates so that they end with .html.php. Although, as far as your web server is concerned, these are still .php files, the .html.php suffix serves as a useful reminder that these files contain both HTML and PHP code.

Many Templates, One Controller

What’s nice about using include statements to load your PHP template files is that you can have multiple include statements in a single PHP script, and have it display different templates under different circumstances!

A PHP script that responds to a browser request by selecting one of several PHP templates to fill in and send back is commonly called a controller. A controller contains the logic that controls which template is sent to the browser.

Let’s revisit one more example from earlier in this chapter: the welcome form that prompts a visitor for a first and last name.

We’ll start with the PHP template for the form. For this, we can just reuse the welcome8.html file we created earlier. Create a directory named welcome and save a copy of welcome8.html called form.html.php into this directory. The only code you need to change in this file is the action attribute of the <form> tag:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"    
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">    
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">    
 <head>    
   <title>Form Example</title>    
   <meta http-equiv="content-type"    
       content="text/html; charset=utf-8"/>    
 </head>    
 <body>    
   <form action="" method="post">    
     <div><label for="firstname">First name:    
       <input type="text" name="firstname" id="firstname"/></label>    
     </div>    
     <div><label for="lastname">Last name:    
       <input type="text" name="lastname" id="lastname"/></label>    
     </div>    
     <div><input type="submit" value="GO"/></div>    
   </form>    
 </body>    
</html>

As you can see, we’re leaving the action attribute blank. This tells the browser to submit the form back to the same URL from which it received the form—in this case, the URL of the controller that included this template file.

Let’s take a look at the controller for this example. Create an index.php script in the welcome directory alongside your form template. Type the following code into this file:

<?php    
if (!isset($_REQUEST['firstname']))    
{    
 include 'form.html.php';    
}    
else3    
{    
 $firstname = $_REQUEST['firstname'];    
 $lastname = $_REQUEST['lastname'];    
 if ($firstname == 'Kevin' and $lastname == 'Yank')    
 {    
   $output = 'Welcome, oh glorious leader!';    
 }    
 else    
 {    
   $output = 'Welcome to our web site, ' .    
       htmlspecialchars($firstname, ENT_QUOTES, 'UTF-8') . ' ' .    
       htmlspecialchars($lastname, ENT_QUOTES, 'UTF-8') . '!';    
 }    
   
 include 'welcome.html.php';5    
}    
?>

This code should look fairly familiar at first glance; it’s a lot like the welcome8.php script we wrote earlier. Let me explain the differences:

if (!isset($_REQUEST['firstname']))    
{


The first thing the controller needs to do is decide whether the current request is a submission of the form in form.html.php or not. You can do this by checking if the request contains a firstname variable. If it does, PHP will have stored the value in $_REQUEST['firstname'].

isset is a built-in PHP function that will tell you if a particular variable (or array element) has been assigned a value or not. If $_REQUEST['firstname'] has a value, isset($_REQUEST['firstname']) will be true. If $_REQUEST['firstname'] lacks a value, isset($_REQUEST['firstname']) will be false.

For the sake of readability, I like to put the code that sends the form first in my controller. What we need this if statement to check, therefore, is if $_REQUEST['firstname'] is not set. To do this, we use the not operator (!). By putting this operator before the name of a function, you reverse the value that function returns from true to false, or from false to true.

Thus, if the request does not contain a firstname variable, then !isset($_REQUEST['firstname']) will return true, and the body of the if statement will be executed.

include 'form.html.php';

If the request is not a form submission, the controller includes the form.html.php file to display the form.

}    
else    
{

If the request is a form submission, the body of the else statement is executed instead.

This code pulls the firstname and lastname variables out of the $_REQUEST array, and then generates the appropriate welcome message for the name submitted:

$firstname = $_REQUEST['firstname'];    
$lastname = $_REQUEST['lastname'];    
if ($firstname == 'Kevin' and $lastname == 'Yank')    
{    
 $output = 'Welcome, oh glorious leader!';    
}    
else    
{    
 $output = 'Welcome to our web site, ' .    
     htmlspecialchars($firstname, ENT_QUOTES, 'UTF-8') . ' ' .    
     htmlspecialchars($lastname, ENT_QUOTES, 'UTF-8') . '!';    
}

Instead of echoing the welcome message, the controller stores the welcome message in a variable named $output.

 include 'welcome.html.php';    
}


After generating the appropriate welcome message, the controller includes the welcome.html.php template, which will display that welcome message.

All that’s left is to write the welcome.html.php template. Here it is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"    
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">    
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">    
 <head>    
   <title>Form Example</title>    
   <meta http-equiv="content-type"    
       content="text/html; charset=utf-8"/>    
 </head>    
 <body>    
   <p>    
     <?php echo $output; ?>    
   </p>    
 </body>    
</html>

That’s it! Fire up your browser and point it at http://localhost/welcome/ (or http://localhost:8080/welcome/ or similar if you need to specify a port number for your web server). You’ll be prompted for your name, and when you submit the form, you’ll see the appropriate welcome message. The URL should stay the same throughout this process.

One of the benefits of maintaining the same URL throughout the process of prompting the user for a name and displaying the welcome message is that the user can bookmark the page at any time during this process and gain a sensible result: when the user next returns, whether the form page or the welcome message was bookmarked, the form will be present itself once again. In the previous version of this example, where the welcome message had its own URL, returning to that URL without submitting the form would have generated a broken welcome message (“Welcome to our web site, !”).

Why So Forgetful?

In Chapter 9, Cookies, Sessions, and Access Control I’ll show you how to remember the user’s name between visits.

Bring On the Database

In this chapter, we’ve seen the PHP server-side scripting language in action as we’ve explored all the basic language features: statements, variables, operators, comments, and control structures. The sample applications we’ve seen have been reasonably simple, but despite this we’ve taken the time to ensure they have attractive URLs, and that the HTML templates for the pages they generate are uncluttered by the PHP code that controls them.

As you may have begun to suspect, the real power of PHP is in its hundreds (even thousands) of built-in functions that let you access data in a MySQL database, send email, dynamically generate images, and even create Adobe Acrobat PDF files on the fly.

In Chapter 4: Publishing MySQL Data on the Web, we’ll delve into the MySQL functions built into PHP, and see how to publish the joke database we created in Chapter 2: Introducing MySQL to the Web. This chapter will set the scene for the ultimate goal of this book—creating a complete content management system for your web site in PHP and MySQL.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links

Rate This Article

  • 1
    Poor
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
    Great

Comment on This Article

Have something to say?

Post A Comment

You need to be a member of the SitePoint Forums to comment on this post. Sign Up

Already a member? Post using your SitePoint Forums account: