Chapter 2
In This Chapter
Understanding the relationship between HTML and PHP
Using the date( ) function
Formatting date and time information
Creating HTML forms designed to work with PHP
Choosing between get and post data transmission
Retrieving data from your HTML forms
Working with HTML form elements
PHP is almost never used on its own. PHP is usually used in tight conjunction with HTML. Many languages have features for creating input forms and user interfaces, but with PHP, the entire user experience is based on HTML. The user never really sees any PHP. Most of the input to PHP programs comes from HTML forms, and the output of a PHP program is an HTML page.
In this chapter, you discover how to integrate PHP and HTML. You explore how PHP code is embedded into HTML pages, how HTML forms can be written so they will send information to a PHP program, how to write a PHP program to read that data, and how to send an HTML response back to the user.
PHP is a different language than HTML, but the two are very closely related. It may be best to think of PHP as an extension that allows you to do things you cannot do easily in HTML. See Figure 2-1 for an example.
Every time you run getTime.php, it generates the current date and time and returns these values to the user. This would not be possible in ordinary HTML because the date and time (by definition) always change. While you could make this page using JavaScript, the PHP approach is useful for demonstrating how PHP works. First, take a look at the PHP code:
<!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>showDate.php</title>
</head>
<body>
<h1>Getting the Time, PHP Style</h1>
<?php
print "<h2>Date: ";
print date("m-d");
print "</h2>
";
print " <h2>Time: ";
print date("h:i");
print "</h2>";
?>
</body>
</html>
The PHP code has some interesting characteristics:
If you view showDate.php in your browser, you won't see the PHP code. Instead, you'll see an HTML page. It's even more interesting when you use your browser to view the page source. Here's what you'll see:
<!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>showDate.php</title>
</head>
<body>
<h1>Getting the Time, PHP Style</h1>
<h2>Date: 07-05</h2>
<h2>Time: 03:50</h2>
</body>
</html>
The remarkable thing is what you don't see. When you look at the source of showDate.php in your browser, the PHP is completely gone! This is one of the most important points about PHP: The browser never sees any of the PHP. The PHP code is converted completely to HTML before anything is sent to the browser. This means that you don't need to worry about whether a user's browser understands PHP. Because the user never sees your PHP code (even if he views the HTML source), PHP code works on any browser, and is a touch more secure than client-side code.
You can send data to a PHP program from an HTML form. For an example of this technique, see askName.html in Figure 2-2.
HTML forms (described fully in Book I, Chapter 7) allow the user to enter data onto a web page. However, HTML cannot respond to a form on its own. You need some sort of program to respond to the form. Book IV describes how to use JavaScript to respond to forms, but you can also write PHP code to handle form-based input. When the user submits the form, the askName.html disappears completely from the browser and is replaced with greetUser.php, as shown in Figure 2-3.
The greetUser.php program retrieves the data from the previous page (askName.html, in this case) and returns an appropriate greeting.
The askName.html program is a standard HTML form, but it has a couple of special features which make it suitable for PHP processing. (See Book I, Chapter 7 for more information about how to build HTML forms.) Here is the HTML code:
<!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>askName.html</title>
</head>
<body>
<form action = "greetUser.php"
method = "get">
<fieldset>
<label>Please enter your name</label>
<input type = "text"
name = "userName" />
<button type = "submit">
submit
</button>
</fieldset>
</form>
</body>
</html>
To build a form designed to work with PHP, there are a few special steps to take:
This page is a regular HTML page. Begin with the same HTML framework you use for building your standard HTML pages. You can use CSS styles, if you wish (but I'm leaving them out of this simple example).
Normally, you can create an HTML document anywhere you want, but this is not so when your page will be working with PHP. This page is meant to be paired with a PHP document. PHP documents will run only if they are in a server's file space, so you should save your HTML document under htdocs to be sure it will call the PHP form correctly.
The form element has an attribute called action. The action attribute is used to determine which program should receive the data transmitted by the form. I want this data to be processed by a program called greetUser.php, so I set greetUser.php as the action:
<form action = "greetUser.php"
method = "get">
The method attribute indicates how the form data will be sent to the server. For now, use the get method. See the section “Choosing the Method of Your Madness,” later in this chapter, for information on the various methods available:
<form action = "greetUser.php"
method = "get">
The point of a form is to get information from the user and send it to a program on the server. Devise a form to ask whatever questions you want from the server. My form is as simple as possible, with one text field, but you can use any HTML form elements you want:
<form action = "greetUser.php"
method = "get">
<fieldset>
<label>Please enter your name</label>
<input type = "text"
name = "userName" />
<button type = "submit">
submit
</button>
</fieldset>
If you want a form element to be passed to the server, you must give it a name attribute. Note: This is a different attribute than id, which is used in client-side processing.
<input type = "text"
name = "userName" />
The name attribute will be used by the PHP program to extract the information from the form.
A form element can have both a name and an ID, if you wish. The name attribute will be used primarily by server-side programs, and the id attribute is mainly used for CSS and JavaScript. The name and ID can (and usually do) have the same value.
The most important difference between a client-side form and a form destined for processing on the server is the button. A special submit button packages all the data in the form and passes it to the program indicated in the action property. Submit buttons can be created in two forms:
<input type = "submit" value = "click me"/>
or
<button type = "submit">click me</button>
Specify submit as the button's type attribute to ensure the button sends the data to the server.
If your form has a submit button and a blank action attribute, the current page will be reloaded.
PHP code is usually a two-step process. First, you create an HTML form, and then you send that form to a PHP program for processing. Be sure to read the previous section on “Creating a form for PHP processing” because now I show you how to read that form with a PHP program.
The HTML form in the last section pointed to a program named greetUser.php. This tells the server to go to the same directory that contained the original HTML document (askName.html) and look for a program named greetUser.php in that directory. Because greetUser is a PHP program, the server passes it through PHP, which will extract data from the form. The program then creates a greeting using data that came from the form. Look over all the code for greetUser.php before I explain it in more detail:
<!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>greetUser.php</title>
</head>
<body>
<?php
$userName = filter_input(INPUT_GET, "userName");
print "<h1>Hi, $userName!</h1>";
?>
</body>
</html>
greetUser.php is not a complex program, but it shows the most common use of PHP: retrieving data from a form. Here's how you build it:
This program should be in the same directory as askName.html, which should be somewhere the server can find (usually under the htdocs or public_html directory).
PHP programs are usually wrapped inside ordinary HTML, so begin the document as if it were plain HTML. Use whatever CSS styling and ordinary HTML tags you want. (I'm keeping this example as simple as possible, although I'd normally add some CSS styles to make the output less boring.)
Somewhere in the page, you'll need to switch to PHP syntax so that you can extract the data from the form. Use the <?php symbol to indicate the beginning of your PHP code:
<?php
$userName = filter_input(INPUT_GET, "userName");
print "<h1>Hi, $userName!</h1>";
?>
All of the data that was sent from the form is stored in a special variable in memory. There are a number of ways to extract that data, but the preferred method is to use the filter_input() function as I have done here. This function takes two parameters: The first is a constant determining the type of input (I'm looking for input passed through the GET mechanism here). The second parameter is the name associated with the form element. Typically you'll make a PHP variable with the same name as the corresponding form element.
See the upcoming section “Getting data from the form” for more information on the filter_input() mechanism and some of the other tools that are available for retrieving information.
Now, your PHP program has a variable containing the user's name, so you can print a greeting to the user. Remember that all output of a PHP program is HTML code, so be sure to embed your output in a suitable HTML tag. I'm putting the greeting inside a level-one heading:
print "<h1>Hi, $userName!</h1>";
The key to server-side processing is adding method and action properties to your HTML form. You have two primary choices for the method property:
The get method is easy to understand. View getRequest.php after it has been called from askName.html in Figure 2-4. Pay careful attention to the URL in the address bar.
The address sent to the PHP program has additional material appended:
http://localhost/haio/book_5/chap_2/greetUser.php?userName=Andy+Harris
Most of this address is the (admittedly convoluted) address of the page on my test server. The interesting part is the section after greetUser.php:
greetUser.php?userName=Andy+Harris
This line shows exactly how the get method passes information to the program on the server:
URL?field1=value1&field2=value2
Sometimes, the spaces are converted to %20 symbols, rather than + signs. It isn't really that important because the conversion is done automatically. Just know that URLs can't contain spaces.
If you understand how the get method works, you can take advantage of it to send data to programs without the original form. For example, take a look at this address:
http://www.google.com/search?q=dramatic+chipmunk
If you type this code into your browser's location bar, you'll get the Google search results for a classic five-second video. (If you haven't seen this video, it's worth viewing.) If you know a particular server-side program (like Google's search engine) uses the get protocol, and you know which fields are needed (q stands for the query in Google's program), you can send a request to a program as if that request came from a form.
You can also write a link with a preloaded search query in it:
<a href = "http://www.google.com/search/q=dramatic+chipmunk">
Google search for the dramatic chipmunk
</a>
If a user clicks the resulting link, he would get the current Google search for the dramatic chipmunk video. (Really, it's a prairie dog, but “dramatic chipmunk” just sounds better.)
The GET method is easy to understand because it sends all data directly in the URL. This makes it easy to see what's going on, but there are some downsides to using get:
The answer to the limitations of the get method is another form of data transmission: the post method.
Here’s how it works:
<form action = "greetUser.php"
method = "post">
The post method is often preferable to get because
The preferred way to extract data from the form is the filter_input() function. This powerful tool not only extracts data from the form, but it also protects against certain kinds of attacks and allows you to sanitize your data before you use it. Filter input requires two or three parameters:
Sanitizing filters all begin with the phrase FILTER_SANITIZE, and they are designed to strip off various types of characters. FILTER_SANITIZE_STRING removes or converts any special characters, and FILTER_SANITIZE_EMAIL removes any character not allowed in an e-mail address. There are filters for all the main data types (int and float) as well as special web-specific filters (e-mail, URL, special HTML characters).
Validation filters do not actually load the value, but check to see that it is in an acceptable format. They all begin with FILTER_VALIDATE and return a Boolean expressing whether the variable passed the validation. Typically you'll validate a variable before you accept it to prevent hackers from passing malicious code to your programs.
If you don't indicate a filter, the FILTER_SANITIZE_STRING filter is automatically applied, which does give you one level of protection. A list of the most commonly used filters is presented in Table 2-1.
Table 2-1 Standard PHP Filters
Filter |
Description |
FILTER_SANITIZE_STRING |
Strips tags, encodes or removes special characters. |
FILTER_SANITIZE_SPECIAL_CHARS |
Converts HTML special characters (<>&) with ASCII equivalents. |
FILTER_SANITIZE_EMAIL |
Removes any characters not allowed in an e-mail address. |
FILTER_SANITIZE_URL |
Removes any characters not allowed in a URL. |
FILTER_SANITIZE_NUMBER_INT |
Removes all characters but numeric digits and sign (+/-) symbols |
FILTER_SANITIZE_NUMBER_INT |
Removes all characters but numeric digits, periods, commas, and sign (+/-) symbols. |
FILTER_VALIDATE_INT |
True if input is an int. |
FILTER_VALIDATE_FLOAT |
True if input is a floating point value. |
FILTER_VALIDATE_BOOLEAN |
True if input can be read as a Boolean (true/false, on/off, yes/no, 1/0). Returns NULL if input is non-Boolean. |
FILTER_VALIDATE_URL |
True if input is a legal URL (doesn't check the address). |
FILTER_VALIDATE_EMAIL |
True if input is a legal e-mail address (doesn't check the address). |
FILTER_VALIDATE_IP |
True if input is a valid IP address (doesn't check the address). |
FILTER_VALIDATE_REGEXP |
True if input matches a given regular expression. (See more about regular expressions in Book IV, Chapter 5.) |
There are few more filters, and some have optional parameters, so you may need to look at the online documentation to get all the details. Ninety percent of the time, you'll just stick with the default FILTER_SANITIZE_STRING filter.
It's just as easy to get data from drop-down lists and radio buttons as it is to get data from text fields. In PHP (unlike JavaScript), you use exactly the same technique to extract data from any type of form element.
For an example of a more complex form, look over monty.html in Figure 2-5. This program is a tribute to my favorite movie of all time. (You might just have to rent this movie if you're really going to call yourself a programmer. It's part of the culture.)
The HTML form poses the questions. (Check out Book I, Chapter 7 for a refresher on HTML forms, if you need it.) Here's the code:
<!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>monty.html</title>
<link rel = "stylesheet"
type = "text/css"
href = "monty.css" />
</head>
<body>
<h1>Monty Python Quiz</h1>
<form action = "monty.php"
method = "post">
<fieldset>
<p>
<label>What is your name?</label>
<select name = "name">
<option value = "Roger">
Roger the Shrubber
</option>
<option value = "Arthur">
Arthur, King of the Britons
</option>
<option value = "Tim">
Tim the Enchanter
</option>
</select>
</p>
<p>
<label>What is your quest?</label>
<span>
<input type = "radio"
name = "quest"
value = "herring" />
To chop down the mightiest tree in the forest
with a herring
</span>
<span>
<input type = "radio"
name = "quest"
value = "grail" />
I seek the holy grail.
</span>
<span>
<input type = "radio"
name = "quest"
value = "shrubbery" />
I'm looking for a shrubbery.
</span>
</p>
<p>
<label>How can you tell she's a witch?</label>
<span>
<input type = "checkbox"
name = "nose"
value = "nose"/>
She's got a witch nose.
</span>
<span>
<input type = "checkbox"
name = "hat"
value = "hat"/>
She has a witch hat.
</span>
<span>
<input type = "checkbox"
name = "newt"
value = "newt" />
She turned me into a newt.
</span>
</p>
<button type = "submit">
Submit
</button>
</fieldset>
</form>
</body>
</html>
There's nothing too crazy about this code. Please note the following features:
The monty.php program is designed to respond to monty.html. You can see it respond when I submit the form in monty.html, as shown in Figure 2-6.
This program works like most PHP programs: It loads data from the form into variables and assembles output based on those variables. Here's the PHP code:
<!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>monty.php</title>
<!-- Meant to run from monty.html -->
</head>
<body>
<h1>Monty Python quiz results</h1>
<?php
//gather the variables
$name = filter_input(INPUT_POST, "name");
$quest = filter_input(INPUT_POST, "quest");
//don't worry about check boxes yet; they may not exist
//send some output
$reply = <<< HERE
<p>
Your name is $name.
</p>
<p>
Your quest is $quest.
</p>
HERE;
print $reply;
//determine if she's a witch
$witch = false;
//See if check boxes exist
if (filter_has_var(INPUT_POST, "nose")){
$witch = true;
}
if (filter_has_var(INPUT_POST, "hat")){
$witch = true;
}
if (filter_has_var(INPUT_POST, "newt")){
$witch = true;
}
if ($witch == true){
print "<p>She's a witch!</p>
";
} // end if
?>
</body>
</html>
If you want to respond to a form with multiple types of data, here's how it's done:
Be sure you know the names of all the fields in the form because your PHP program will need this information.
Use your standard HTML framework as the starting point for your PHP documents, too. The results of your PHP code should still be standards-compliant HTML. Use the <?php and ?> symbols to indicate the presence of PHP code.
Use the $_REQUEST technique described in the “Receiving data in PHP” section of this chapter to extract form data and store it in local variables:
//gather the variables
$name = filter_input(INPUT_POST, "name");
$quest = filter_input(INPUT_POST, "quest");
Don't worry about the check boxes yet. Later on, you'll determine whether they exist. You don't really care about their values.
PHP programming almost always involves constructing an HTML document influenced by the variables that were extracted from the previous form. The heredoc method (described in Chapter 1 of this minibook) is an ideal method for packaging output:
//send some output
[ $reply = <<< HERE
[ <p>
Your name is $name.
</p>
<p>
Your quest is $quest.
</p>
[HERE;
[ print $reply;
Check boxes are the one exception to the “treat all form elements the same way” rule of PHP. The important part of a check box isn't really its value. What you really need to know is whether the check box is checked. Here's how it works: If the check box is checked, a name and value are passed to the PHP program. If the check box is not checked, it's like the variable never existed:
Each check box, if checked, would be proof that she’s a witch. The filter_has_var() function is used to determine whether a particular variable exists. This function takes an input type and a variable name (just like filter_input()) and returns true if the variable exists and false if it doesn’t.
After testing for the existence of all the check boxes, the $witch variable will still be false if none of the check boxes were checked. If any combination of check boxes is checked, $witch will be true:
//determine if she's a witch
$witch = false;
//See if check boxes exist
if (filter_has_var(INPUT_POST, "nose")){
$witch = true;
}
if (filter_has_var(INPUT_POST, "hat")){
$witch = true;
}
if (filter_has_var(INPUT_POST, "newt")){
$witch = true;
}
if ($witch == true){
print "<p>She's a witch!</p>
";
} // end if