Tuesday, August 11, 2009

Putting It All Together

he previous chapters of this book provide you with the tools that you need to build your Web database application. In Part I, you find out how
PHP and MySQL work and how to get access to them. In addition, you dis­ cover what needs to be done to build your application and in what order to do it. In Part II, you find out how to build and use a MySQL database. In Part III, you discover what features PHP has and how to use them. In addition, this part also explains how to show information in a Web page, collect informa­ tion from users, and store information in a database. Now you’re ready to put it all together.

In this chapter, I show you how to put all the pieces together into a complete application. To do this, you need to

Organize the application

Make sure that the application is secure

Document the application

Here, I describe each of these steps in detail.

Organizing the Application

Organizing the application is for your benefit. As far as PHP is concerned, the application could be 8 million PHP statements all on one line of one computer file. PHP doesn’t care about lines, indents, or files. However, humans write
and maintain the programs for the application, and humans need organiza­
tion. Applications require two levels of organization:

The application level: Most applications need more than one program to deliver complete functionality. You must divide the functions of the application into an organized set of programs.

The program level: Most programs perform more than one specific task. You must divide the tasks of the program into sections within the program.

Organizing at the application level

In general, Web database applications consist of one program per Web page. For instance, you might have a program that provides a form to collect infor­ mation and a program that stores the information in a database and tells the user that the data has been stored.

Another basis for organization is one program per major task. For instance, you might have a program to present the form and a program that stores the data in a database. For Web applications, most major tasks involve sending a Web page. Collecting data from the user requires a Web page for the HTML (HyperText Markup Language) form; providing product information to cus­ tomers requires Web pages; and when you store data in a database, you usu­ ally want to send a confirmation page to the user that the data was stored.

One program per Web page or one program per major task is not a rule but merely a guideline. The only rule regarding organization is that it must be clear and easy to understand. And that’s totally subjective. Still, the organiza­ tion of an application such as the Pet Catalog need not be overly compli­ cated. Suppose that the Pet Catalog design calls for the first page to list all
the pet types — such as cat, dog, and bird — that the user can select from. Then, after the user selects a type, all the pets in the catalog for that type are shown on the next Web page. A reasonable organization would be two pro­ grams: one to show the page of pet types and one to show the pets based on the pet type that was chosen.

Here are a few additional pointers for organizing your programs:

Choose very descriptive names for the programs in your application.
Program names are part of the documentation that makes your applica­ tion understandable. For instance, useful names for the Pet Catalog pro­ grams might be ShowPetTypes.php and ShowPets.php. It’s usual, but not a requirement, to begin the program names with an uppercase letter. Case isn’t important for program names on Windows computers, but it’s very important on Unix/Linux computers. Pay attention to the upper- lowercase letters so that your programs can run on any computer if needed.

Put program files into subdirectories with meaningful names. For instance, put all the graphic files into a directory called images. If you only have three files, you may be okay with only one directory, but look­ ing through dozens of files for one specific file can waste a lot of time.

Organizing at the program level

A well-organized individual program is very important for the following reasons:

It’s easier for you to write. The better organized your program is, the easier it is for you to read and understand it. You can see what the pro­ gram is doing and find and fix problems faster.

It’s easier for others to understand. Others may need to understand your program. After you claim that big inheritance and head off to the South Sea Island that you purchased, someone else will have to maintain your application.

It’s easier for you to maintain. No matter how thoroughly you test it, your application is likely to have a problem or two. The better organized your program is, the easier it is for you to find and fix problems, espe­ cially six months later.

It’s easier to change. Sooner or later, you or someone else will need to change the program. The needs of the user may change. The needs of the business may change. The technology may change. The ozone layer may change. For one reason or another, the program will need to be changed. Figuring out what the program does and how it does it so that you can change it is much easier if it is well organized. I guarantee that you won’t remember the details; you just need to be able to understand the program.

The following rules will produce well-organized programs. I hesitate to call them rules because there can be reasons in any specific environment to break one or more of the rules, but I strongly recommend thinking carefully before breaking any of the following rules:

Divide the statements into sections for each specific task. Start each section with a comment describing what the section does. Separate sec­ tions from each other by adding blank lines. For instance, for the Pet Catalog, the first program might have three sections for three tasks:

1. Echo introductory text, such as the page heading and instruc­ tions. The comment before the section might be /* opening text */. If the program echoes a lot of complicated text and
graphics, you might make it into more than one section, such as /*
title and logo */ and /* instructions */.

2. Get a list of pet types from the database. If this section is long and complicated, you can divide it into smaller sections, such as 1) connect to database; 2) execute SELECT query; and 3) put data into variables.

3. Create a form that displays a selection list of the pet types. Forms are often long and complicated. It can be useful to have a section for each part of the form.

Use indents. Indent blocks in the PHP statements. For instance, indent if blocks and while blocks as I have done in the sample code for this book. If blocks are nested inside other blocks, indent the nested block even further. It’s much easier to see where blocks begin and end when they’re indented, which in turn makes it easier to understand what the program does. Indenting the HTML statements can also be helpful. For instance, if you indent the lines between the open and close tags for a form or between the <table> tag and the </table> tag, you can more easily see what the statements are doing.

Use comments liberally. Definitely add comments at the beginning that explain what the program does. And add comments for each section. Also, comment any statements that you think aren’t obvious or state­ ments where you think you may have done something in an unusual way. If it took you a while to figure out how to do it, it’s probably worth commenting. Don’t forget short comments on the end of lines; some­ times just a word or two can help.

Use simple statements. Sometimes programmers get carried away with the idea of concise code to the detriment of readability. Nesting six func­ tion calls inside each other may save some lines and keystrokes, but it will also make the program more difficult to read.

Reuse blocks of statements. If you find yourself typing the same ten lines of PHP statements in several places in the program, you can move that block of statements into another file and call it when you need it. One line in your program that reads getData() is much easier to read than ten lines that get the data. Not only that, if you need to change something within those lines, you can change it in one external file instead of having to find and change it a dozen different places in your program. There
are two ways to reuse statements: functions and include statements. Chapter 7 explains how to write and use functions. The following two sec­ tions explain the use of functions and include statements in program organization.

Use constants. If your program uses the same value many times, such as the sales tax for your state, you can define a constant in the beginning of the program that creates a constant called CA_SALES_TAX that is .97
and use it whenever it’s needed. Defining a constant that gives the number a name helps anyone reading the program understand what the number is — plus, if you ever need to change it, you only have to change it in one place. Constants are described in detail in Chapter 6.

Using include statements
PHP allows you to put statements into an external file — that is, a file sepa­ rate from your program — and to insert the file wherever you want it in the program by using an include statement. include files are very useful for storing a block of statements that is repeated. You add an include statement wherever you want to use the statements instead of adding the entire block
of statements at several different locations. It makes your programs much shorter and easier to read. The format for an include statement is

include(“filename”);

The file can have any name. I like to use the extension .inc. The statements in the file are included, as-is, at the point where the include statement is used. The statements are included as HTML, not PHP. Therefore, if you want to use PHP statements in your include file, you must include PHP tags in the include file. Otherwise, all the statements in the include file are seen as HTML and output to the Web page as-is.

Here are some ways to use include files to organize your programs:

Put all or most of your HTML into include files. For instance, if your program sends a form to the browser, put the HTML for the form into
an external file. When you need to send the form, use an include state­
ment. Putting the HTML into an include file is a good idea if the form is shown several times. It is even a good idea if the form is shown only once because it makes your program much easier to read. The programs in Chapters 11 and 12 put HTML code for forms into separate files and include the files when the forms are displayed.

Store the information needed to access the database in a file separate from your program. Store the variable names in the file as follows:

<?php
$host=”localhost”;
$user=”root”;
$password=””;
?>

Notice that this file needs the php tags in it because the include state­ ment inserts the file as HTML. Include this file at the top of every program that needs to connect to the database. If any of the information (such as the password) changes, just change the password in the include file. You don’t need to search through every program file to change the password. For a little added security, it’s a good idea to use a misleading filename, rather than something obvious like secret_passwords.inc.

Put your functions in include files. You don’t need the statements for functions in the program; you can put them in an include file. If you have a lot of functions, organize related functions into several include files, such as data_functions.inc and form_functions.inc. Use include statements at the top of your programs, reading in the func­ tions that are used in the program.

Store statements that all the files on your Web site have in common.
Most Web sites have many Web pages with many elements in common. For instance, all Web pages start with <html>, <head>, and <body> tags. If you store the common statements in an include file, you can include them in every Web page, ensuring that all your pages look alike. For instance, you might have the following statements in an include file:

<html>
<head><title><?php echo $title ?></title></head>
<body topmargin=”0”>
<p align=”center”><img src=”logo.gif” width=”100”
height=”200”>
<hr color=”red”>

If you include this file in the top of every program on your Web site, you save a lot of typing, and you know that all your pages match. In addition, if you want to change anything about the look of all your pages, you only have to change it one place — in the include file.

You can use a similar statement as follows:

include_once(“filename”);

This statement prevents include files with similar variables from overwriting each other. Use include_once when you include your functions.

You can use a variable name for the filename as follows:

include(“$filename”);

For example, you might want to display different messages on different days. You might store these messages in files that are named for the day on which the message should display. For instance, you could have a file named Sun.inc with the following contents:

<p>Go ahead. Sleep in. No work today.</p>

And similar files for all days of the week. The following statements can be used to display the correct message for the current day:

$today = date(“D”);
include(“$today”.”.inc”);

After the first statement, $today contains the day of the week, in abbrevia­ tion form. The date statement is discussed in Chapter 6. The second state­ ment includes the correct file, using the day stored in $today. If $today contains Sun, the statement includes a file called Sun.inc.

Protecting your include files is important. The best way to protect them is
to store the include files in a directory outside your Web space so they can’t be accessed by visitors to your Web site.

You can set up an include directory where PHP looks for any files specified in an include statement. If you are the PHP administrator, you can set up
an include directory in the php.ini file (the PHP configuration file in your system directory, as I describe in Appendix B). Find the setting for include_ path and change it to the path to your preferred directory. If there is a semi­ colon at the beginning of the line, before include_path, remove it. The fol­ lowing are examples of include_path settings in the php.ini file:

include_path=”.;d:\include”; # for Windows include_path=”.:/user/local/include”; # for Unix/Linux/Mac

Both of these statements specify two directories where PHP looks for include
files. The first directory is dot (meaning the current directory), followed by the second directory path. You can specify as many include directories as you want, and PHP will search them for the include file in the order in which they are listed. The directory paths are separated by a semicolon for Windows and a colon for Unix/Linux.

If you don’t have access to php.ini, you can set the path in each individual script by using the following statement:

ini_set(“include_path”,”d:\hidden”);

This statement sets the include_path to the specified directory only while the program is running. It doesn’t set the directory for your entire Web site.

To access a file from an include directory, just use the filename, as follows. You don’t need to use the full path name.

include(“secretpasswords.inc”);

If your include file is not in an include directory, you may need to use the entire path name in the include statement. If the file is in the same directory as the program, the filename alone is sufficient. However, if the file is located in another directory, such as a subdirectory of the directory that the pro­ gram is in or a hidden directory outside the Web space, you need to use the full path name to the file, as follows:

include(“d:/hidden/secretpasswords.inc”);

Using functions
Make frequent use of functions to organize your programs. ( In Chapter 7, I discuss creating and using functions in detail.) Functions are useful when your program needs to perform the same task at repeated locations in a pro­ gram or in different programs in the application. After you write a function that does the task and you know it works, you can use it anywhere that you need it.

Look for opportunities to use functions. Your program is much easier to read and understand with a line like this:

getMemberData();

than with 20 lines of statements that actually get the data.

In fact, after you’ve been writing PHP programs for a while, you will have a stash of functions that you’ve written for various programs. Very often the program that you’re writing can use a function that you wrote for an applica­ tion two jobs ago. For instance, I often have a need for a list of the states. Rather than include a list of all 50 states every time that I need it, I have a function called getStateNames() that returns an array that holds the 50 state names in alphabetical order and a function called getStateCodes() that returns an array with all 50 two-letter state codes in the same order. These functions are frequently useful.

Name your functions very descriptively. The function calls in your program should tell you exactly what the function does. Long is okay. You don’t want to see a line in your program that reads

function1();

This line isn’t very informative. Even a line like the following is less informa­
tive than it could be:

getData();

You want to see a line like this:

getAllMemberNames();

Keeping It Private

You need to protect your Web database application. People out there may have nefarious designs on your Web site for purposes such as

Stealing stuff: They hope to find a file sitting around full of valid credit card numbers or the secret formula for eternal youth.

Trashing your Web site: Some people think this is funny. Some people do it to prove that they can.

Harming your users: A malicious person can add things to your Web site that harm or steal from the people who visit your site.

This is not a security book. Security is a large, complex issue, and I am not a security expert. Nevertheless, I want to call a few issues to your attention and make some suggestions that might help. The following measures will increase the security of your Web site, but if your site handles really important, secret information, read some security books and talk to some experts:

Ensure the security of the computer that hosts your Web site. This is probably not your responsibility, but you may want to talk to the people responsible and discuss your security concerns. You’ll feel better if you know that someone is worrying about security.

Don’t let the Web server display filenames. Users don’t need to know the names of the files on your Web site.

Hide things. Store your information so that it can’t be easily accessed from the Web.

Don’t trust information from users. Always clean any information that you didn’t generate yourself.

Use a secure Web server. This requires extra work, but it’s important if you have top-secret information.

Ensure the security of the computer

First, the computer itself must be secure. The system administrator of the computer is responsible for keeping unauthorized visitors and vandals out of the system. Security measures include such things as firewalls, encryption, password shadowing, scan detectors, and so on. In most cases, the system administrator is not you. If it is, you need to do some serious investigation into security issues. If you are using a Web-hosting company, you may want
to discuss security with those folks to reassure yourself that they are using sufficient security measures.

Don’t let the Web server display filenames

You may have noticed that sometimes you get a list of filenames when you point at a URL. If you point at a directory (rather than a specific file) and the directory doesn’t contain a file with the default filename (such as index.

html), the Web server may display a list of files for you to select from. You probably don’t want your Web server to do this; your site won’t be very secure if a visitor can look at any file on your site. On other Web sites, you may have seen an error message that reads

Forbidden
You don’t have permission to access /secretdirectory on this server.

On those sites, the Web server is set so that it doesn’t display a list of file­ names when the URL points to a directory. Instead, it delivers this error mes­ sage. This is more secure than listing the filenames. If the filename is being sent from your Web site, a setting for the Web server needs to be changed. If you aren’t the administrator for your Web server, request a change. If you are the administrator, it’s up to you to change this behavior. For instance, in Apache, this behavior is controlled by an option called Indexes, which can be turned on or off in the httpd.conf file as follows:

Options Indexes // turns it on
Options -Indexes // turns it off

See the documentation for your Web server to allow or not allow directory listings in the user’s Web browser.

Hide things

Keep information as private as possible. Of course, the Web pages that you want visitors to see must be stored in your public Web space directory. But not everything needs to be stored there. For instance, you can store include files in another location altogether — in space on the computer that can’t
be accessed from the Web. Your database certainly isn’t stored in your Web space, but it might be even more secure if it were stored on a totally different computer.

Another way to hide things is to give them misleading names. For instance, the include file containing the database variables shouldn’t be called passwords.inc. A better name might be UncleHenrysChickenSoupRecipe. inc. I know this suggestion violates other sections of the book where I pro­ mote informative filenames, but this is a special case. Malicious people some­ times do obvious things like typing www.yoursite.com/passwords.html into their browser to see what happens.

Don’t trust information from users

Malicious users can use the forms in your Web pages to send dangerous text to your Web site. Therefore, never store information from forms directly into a database without checking it first. Check the information that you receive for

reasonable formats and dangerous characters. In particular, you don’t want to accept HTML tags, such as <script> tags, from forms. By using script tags, a user could enter an actual script — perhaps a malicious one. If you just accept the form field without checking it and store it in your database, you could have any number of problems, particularly if the stored script was sent in a Web page to a visitor to your Web site. For more on checking data from forms, see Chapter 8.

Use a secure Web server

Communication between your Web site and its visitors is not totally secure. When the files on your Web site are sent to the user’s browser, someone on the Internet between you and the user can read the contents of these files as they pass by. For most Web sites, this isn’t an issue; however, if your site col­ lects or sends credit card numbers or other secret information, use a secure Web server to protect this data.

Secure Web servers use Security Sockets Layer (SSL) to protect communica­ tion sent to and received from browsers. This is similar to the scrambled tele­ phone calls that you hear about in spy movies. The information is encr ypted (translated into coded strings) before it is sent across the Web. The receiving software decrypts it into its original content. In addition, your Web site uses a certificate that verifies your identity. Using a secure Web server is extra work, but it’s necessary for some applications.

You can tell when you are communicating using SSL. The URL begins with
HTTPS, rather than HTTP.

Information about secure Web servers is specific to the Web server that you’re using. To find out more about using SSL, look at the Web site for the Web server that you are using. For instance, if you are using Apache, check out two open-source projects that implement SSL for Apache at www.modssl. org and www.apache-ssl.org. Commercial software is also available that provides a secure server based on the Apache Web server. If you’re using Microsoft Internet Information Server (IIS), search for SSL on the Microsoft Web site at www.microsoft.com.

Completing Your Documentation

I’m making one last pitch here. Documenting your Web database application
is essential. You start with a plan describing what the application is supposed to do. Based on your plan, you create a database design. Keep the plan and the design up to date. Often as a project moves along, changes are made. Make sure that your documentation changes to match the new decisions.

While you design your programs, associate the tasks in the application plan with the programs that you plan to write. List the programs and what each one will do. If the programs are complicated, you may want to include a brief description of how the program will perform its tasks. If this is a team effort, list who is responsible for each program. When you complete your applica­ tion, you should have the following documents:

Application plan: Describes what the application is supposed to do, list­
ing the tasks that it will perform

Database design: Describes the tables and fields that are in the database

Program design: Describes how the programs will do the tasks in the application plan

Program comments: Describe the details of how the individual program works

Pretend that it’s five years in the future and you’re about to do a major
rewrite of your application. What will you need to know about the application in order to change it? Be sure that you include all the information that you need to know in your documentation.

0 comments: