Building Your First PHP Application - PHP QuickStart Guide (2015)

PHP QuickStart Guide (2015)

Chapter 6: Building Your First PHP Application

The previous chapters have given you all the information you need to write programs in PHP and embed them in web pages. In this chapter, we'll begin creating a working application with an HTML form and a PHP program that processes the information it collects. You'll be creating a basic contact form, useful for ensuring that website owners collect the information necessary to respond to viewers.

As you build the application, you'll learn how to:

- Work with arrays in PHP,
- Import form input as PHP variables,
- Validate form input with PHP,
- Output PHP variable values with “shortcut” code,
- Use PHP to preload values for form inputs,
- Use PHP to determine which HTML to display to a web browser,
- Use PHP to run services on a web server, and
- Concatenate strings in PHP.

Creating the Form

Let's start by creating the basic form. The code block on the following page contains the form with which we'll start. If you're an HTML expert, you'll notice that the page code is very basic. Once you've completed the application and tested it on your website, you may want to add meta tags, etc. as needed for your site. For the purposes of this project, basic HTML will be less confusing.

Copy the code block below to a file and save it as contactform.php.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Contact Form</title>
<p>If you have questions about this site, please use the form below to contact us, so that we can provide the best possible answers.</p>
<p> Fields with <strong>bold</strong> labels are required.</p>
<form method="post" action="contactform.php">
<strong>First Name</strong>
<input type="text" name="fname" size="20"><br>
<strong>Last Name</strong>
<input type="text" name="lname" size="20"><br>
<input type="text" name="phone" size="20"><br>
<strong>Email Address</strong>
<input type="text" name="fname" size="20"><br>
<strong>Type your question below:</strong><br>
<textarea name="msg" cols="50" rows="10"></textarea><br>
<input type="submit" name="submit" value="Send">

Once you've created the new file, go ahead and make it available on your website. Open it in your browser and verify that there are no problems.

There's no need to analyze the HTML code in great detail; the form itself is standard. You'll be making modifications and additions as we proceed. You'll want to note two things about the <form> tag:

1) The form method is “post.” This will be important to our PHP program.

2) The form action is “contactform.php”, which means that the form will be calling the same page on which it resides. Your PHP code will be intelligent enough to determine what action to take when this page is delivered to your browser. This application will be entirely self-contained, all on a single web page!

One more unusual feature on this form is the “name” attribute on the submit button, which is often omitted on an HTML form. This attribute will be important to our application.

Creating the First Control Structure

Now we're ready to start writing PHP code. The first block of code we're going to create will be placed above everything else on the page. That means that when the web server receives a request for contactform.php, it will read that code before sending anything to the browser. This is important for 2 reasons:

1) Web servers and browsers send important information about pages back and forth in data blocks called Hypertext Transfer Protocol (HTTP) headers. The headers are passed before any other information and can only be sent once per request. Because PHP often uses these headers to control certain processes, it's important that the PHP code be placed on the page above the HTML tags, which signal the end of a header.

2) The PHP control structure we'll be writing at this stage will determine how the page is displayed each time the page is accessed.

The first items we'll need are the opening and closing tags for this block of code. Getting into the habit of creating these tags first in order to “set up your work space” will help you avoid errors. We're going to be writing many lines of code in this block, so at the top of your contactform.php file, add these three lines:



Again, be sure to place this block of code at the absolute top of the document. You'll start writing on the blank line in the center. Placing your opening and closing tags this way give you an easy way to find where your PHP code begins and ends later.

Since this program will process the input from the form on our page, we'll need to know whether the form has been submitted when the page loads. (Remember – when a visitor submits the form, the information is sent to this same page.) Let's start by learning how PHP recognizes the input from the form.

Working with Arrays

When a form is submitted on a web page, it sends an HTTP request header to the web server. Along with other information, the header will contain all of the form input field names and the value that was input for each. When the PHP interpreter, remember, this is a PHP page, so it's passed to the interpreter, encounters these inputs, it creates an array of those values, with a special name. Since the form on our page is using the “post” method, the name for the array will be$_POST.

Note:the$_ character sequence is an important one in PHP that designates a predefined (built-in) variable. To avoid confusion, it's best not to use this sequence for your own variable names.

To use a value from a PHP array, we can refer to it directly using its numeric index (position in the array) or its label. The values sent from a form will be assigned keys matching the “name” attributes of the HTML input tags of the form. These variables and the array itself are also assigned a type of “superglobal,” meaning they can be used anywhere in a PHP program.

The syntax for getting the value of an array element by key is:

array name[key].

Thus, the following code:$_POST['fname'] will return the value of the “fname” field in our form. Each input in the form can be read directly into our program in this way.

Note: The single quotes around the label inside the brackets, designating the name as a literal text string. If a variable is used to represent the key, the quotes should be omitted.

Testing for Form Submittal

Let's create the code that determines what to do if the form has been submitted. We'll do this with an “if” control structure and a built-in PHP function:isset.Here's the code:

/*** if the form was submitted, get the input values ***/
if (isset($_POST['submit'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$msg = $_POST['msg'];
} //end the if construct

Note the comments added to clarify each step. Now, let's analyze what this code block does.

First, we use the isset function to test whether the submit button was clicked. You'll recall that we gave that button a name in the HTML code. Our “if” construct tests to see if that name has been set, in other words, whether it exists for our program.

If the submit button was clicked, the button's name will be set and the instructions within the curly braces will be executed. If not, everything within the braces will be ignored and the program will simply move ahead to the next statement.

Declaring Variables

Assuming the form was submitted, our program now assigns simple variable names to each form input value except the submit button, which won't we need for anything else. Note that the single equal sign ( = ) is an assignment operator, used to assign values, rather than to compare them.

Add the code from the block above to your contactform.php code. This is a complete control structure.

Form Input Validation

Now, before we do anything else with the values, remember that we told the visitors that some inputs are required. We can use PHP to “validate” the form input, ensuring that those required fields are filled. To do this, we'll “nest” an “if” control structure inside the one we just completed.

Since we've declared variables for each input, we can now use those variable names instead of the more complex array elements to simplify working with those values. To check each of the required variables, we'll use another built-in function:empty. This function returns a Boolean value of TRUE if a variable name has a null value.

Here's the code we'll add to perform the validation procedure:

/*** test for required inputs ***/
if (empty($fname) || empty($lname) ||
empty($email) || empty($msg)) {
$error = TRUE;

Let's analyze the code block above. First of all, note that the first line of code has been wrapped midway through the parameters to make it easier to read. PHP allows line wrapping between quotes, parentheses, etc. Second, we're introducing a new operator in this code block. The double pipe character (||) is the logical OR operator.

Read aloud, this block of code says, “If $fname is empty or $lname is empty or $email is empty or $msg is empty, then create $error and make it TRUE.” That's the procedure it performs, so if any of the required fields are empty, there will be an error message that we can use later. Note the lack of quotes around the word TRUE. This syntax assigns a Boolean value of TRUE rather than the string “TRUE.”

Note: This is very basic form validation. If a field contains any characters, including the space character, the empty function will return FALSE. More complex validation can be performed with PHP, but that is beyond the scope of this book.

We'll want to perform this test only if the form is submitted, so this code will need to be within the first “if” structure we created. Copy it into your file just below the last line in the structure and above the closing curly brace ( } ). Leave the leading spaces as they are in the code block, to make the program flow easier to trace.

So far, we've checked to see if the form was submitted, and if so, checked to see if all of the required input was submitted. We then defined an error message we can use if any input is missing.

Now it's time to tell the interpreter what we want to do with the information if we have it all. Although there are many options, we're going to use a very convenient and sophisticated built-in PHP function to send the information to you by email.

The Else Condition

First, the way in which we determine whether to move to the next step will introduce you to the beauty of the “if/else” construct. Up to this point, our script (program) says, “If the form has been submitted, get the input values and see if any of the required ones are empty. If any are empty, create $error and make it true.” Now, if none of the required input values are empty, we'll do something “else.”

To create the new “else” conditional statement, we simply add the term to the closing bracket of the “if” with which we're concerned and add another set of braces. Here's how it will look with our last block:

/*** test for required inputs ***/
if (empty($fname) || empty($lname) ||
empty($email) || empty($msg)) {
$error = TRUE;
} else {

} //end if/else construct

The obvious next step is to create the instructions for the else condition. In this case, we've run our tests and we're ready to create and send an email containing the information from the form. We'll do that with a built-in PHP function that sends commands to the web server's email service, i.e. the programs that send and receive email. The function name ismail.

The Mail Function

In order to easily provide the mail function with all the necessary parameters, we'll declare some variables and assign the message information as values. While we're at it, you'll learn how to use two new operators. We'll start with a couple of straightforward variables:

/*** send email ***/
$recipient = '';
$subject = 'Website contact';

Change '' to your own email address in the above code.

Next, we'll build the body of the email message, the part you'll read, one line at a time, using a special operator known as the concatenating assignment operator. This operator, also known as the “dot equal” sign ( .=), tells the interpreter that the left string should now be equal to the left string followed by the right string. This makes it very easy to assign long strings to a variable name, as we'll do here:

$body = "The following message was sent";
$body .= " via your website contact form:\n\n";
$body .= "Name: $fname $lname\n";
$body .= "Email: $email\n";
if (empty($phone) == FALSE) {
$body .= "Phone: $phone\n";
$body .= "\n$msg";

In the code above, we started with a variable declaration and assigned it a string value. On the next line, we used the dot equal operator to add another string to the same variable. If we'd used the equal sign, the second string would have replaced the first. Using the ( = ) assignment operator on a variable that already has a value will reassign it using the new value.

Note also that we've used double quotes on these strings. This tells the interpreter to evaluate any operators in the strings and use the value of variables instead of the literal text. You'll see where the variable names for the form input values have been entered. Notice also the escaped “n” character ( \n), which will print a “newline” character to create a line break in your email message.

Lastly, notice the “if” construct we've used to determine whether the visitor provided a phone number and add it to the message. Most importantly, note the double equal sign operator inside the parentheses. This operator is a comparator that checks for equality between the left and right values. We've used the empty function again here, but in this case, we want to verify that the variable contains a value, meaning the empty function will return FALSE.

In the last line of the code block, we add the value of the<textarea> element of the HTML form, completing the body of the email.

The next step in preparing the email is to create a set of headers required by the server and the receiving email client program. We'll use the same basic method as was used to create the email body:

$headers = "From:\r\n";
$headers .= "Reply-to: $email\r\n\r\n";

Change “” to your domain name in the above code.

This completes the process of preparing the information required by the mail function. Now we can provide the information as parameters in the function call quite easily, using the variables we've created. At the same time, we'll create a test procedure to ensure that the email is sent to the server and our mailing application completed successfully:

$sent = (mail($recipient, $subject, $body, $headers));
if ($sent) {
$success = TRUE;

These blocks of code complete the programming we need to do before the HTML output begins, and the next line on the page should contain only the PHP closing tag we added earlier. Save your file again.

Controlling HTML Output with PHP

In addition to sending the form input by email, the script we created in the top of the document created all the elements we need to determine what our page will display each time it's requested. Why would we want to do that? To customize what the visitor sees in response to what action was taken.

In this case, we're going to first present the visitor with the contact form. When the form is submitted, we'll do one of these two things:

1) Present the form again, with the information that was submitted in place, along with an error message if required information is missing

2) Present a nice thank you page if the send was successful

We'll be able to do all of that without sending the visitor to another page simply by using a PHP control structure to determine some of the HTML output. We'll be writing our code in the HTML body and using the alternate control structure syntax described earlier in the book to simplify mixing the HTML and PHP.

On the following page, you'll find the original HTML body with some PHP code blocks added. The PHP code is in bold type for clarity. HTML comments have also been added to help identify the sections of the page.

<?php if ($success): ?>
<?php else: ?>
<?php if ($error): ?>
<?php endif; ?>
<p>If you have questions about this site, please use the form below to contact us, so that we can provide the best possible answers.</p>
<p> Fields with <strong>bold</strong> labels are required.</p>
<form method="post" action="contactform.php">
<strong>First Name</strong>
<input type="text" name="fname" size="20"><br>
<strong>Last Name</strong>
<input type="text" name="lname" size="20"><br>
<input type="text" name="phone" size="20"><br>
<strong>Email Address</strong>
<input type="text" name="fname" size="20"><br>
<strong>Type your question below:</strong><br>
<textarea name="msg" cols="50" rows="10"></textarea><br>
<input type="submit" name="submit" value="Send">
<?php endif; ?>

All we need to do now is add the HTML code we want to display for each condition. Let's start with the “Thank you” message. We'll want the visitor to see this message after the email is successfully sent. Consulting our PHP code, you'll see that when the send was successful, we created a variable named “success” and gave it a Boolean value ofTRUE. Our first “if” statement checks that variable.

Note: if ($success)means the same thing asif($success == TRUE). When testing a Boolean value, it's not necessary to use the longer version.

Let's create a simple message to let the visitor know the operation was a success:

<div style="margin:auto; text-align:center">
<h2>Thank you for contacting us!</h2>
Your email has been sent and we'll respond as quickly as possible.

Place the HTML code above on your page, directly underneath the first HTML comment and above <?phpelse: ?>.

Next, let's create an error message:

<div style="font-weight:bold; color:#ff0000;">
Please enter input for each field with a <strong>bold</strong>label.

This error message should be placed on your page directly under this HTML comment tag: <!-- INPUT MISSING. DISPLAY ERROR MESSAGE -->

That's it! Your page now has everything needed to display HTML code customized to suit each condition.

Populating Form Fields

Now, let's add one more feature. If you've tested your application, and it's working correctly, you'll notice that, if one of the required inputs is missing, it prints an error message, but all the other information that was entered has disappeared. That means that your visitor is going to have to provide that information again.

What if there was a way to preserve that information in the newly displayed form? Fortunately, there is! You'll recall that PHP code can be embedded anywherewithin an HTML document. We can take advantage of that fact by using theecho construct to place the value of the variables we created from the previous inputs in the “value” attribute of our form fields. This is known as populating the form fields.

Let's use another convenient PHP feature to make this process easier. There's a “shortcut” for theecho construct that works nicely for this kind of operation. Instead if typing:

<?php echo "something"?>,

We can use:

<?= "something"?>

To accomplish the same thing. Here's how it looks with the first of our HTML input tags on the form:

<input type="text" name="fname" size="20" value="<?= $fname ?>">

By adding this to each of the input fields on our form using the appropriate variable names, the information your visitor entered before submitting the form will still be there if the form is displayed again. If a form field was left blank, it will, of course, be blank.

Note: Variable names aren't enclosed in quotes when we want to display their values. Using quotes around the name will cause the interpreter to print the name as a string.

If you're wondering, “What about the text for the message?”,good thinking. This form field has to be treated a little differently, but it's still a simple matter. The HTML<textarea>tag is a “container” tag that requires a closing tag:</textarea>. Anything that's typed between the two tags will be displayed in the text box on the form. To place the previously-entered text there, we simply use the shortcut tag to print the value of that variable between them:

<textarea name="msg" cols="50" rows="10">
<?= $msg ?>

Now that your form is populated for the error routine, your application is complete. Make it available on your hosting account and test it thoroughly. If you encounter errors, go back to the beginning of this chapter and check each step in turn.

Note: If you continue to experience problems with your application, use the code provided in Appendix B in a new file to test its compatibility with your host's web server. If that page does not work correctly, chances are there is a compatibility problem. In this case, contact your host's documentation or technical support staff for advice on overcoming the issues.

In addition, it's important to know that differences in email servers may cause unexpected issues with the PHP mail function. If your application appears to work correctly, but you're not receiving the email, first make sure you've entered the email address correctly and then check with your hosting service on how to use remote commands for the email server.