The submit button To match the type of form being submitted, you can change the text of the submit button to anything you like by using the value parameter, like this: You can also repl
Trang 1Example 11-7 Using ‘select’
Vegetables <select name="veg" size="1">
<option value="Peas">Peas</option>
<option value="Beans">Beans</option>
<option value="Carrots">Carrots</option>
<option value="Cabbage">Cabbage</option>
<option value="Broccoli">Broccoli</option>
</select>
This HTML offers five choices with the first one, Peas, preselected (due to it being the
first item) Figure 11-6 shows the output where the list has been clicked on to drop it
down, and the option Carrots has been highlighted If you want to have a different default option offered first (such as Beans), use the selected tag, like this:
<option selected="selected" value="Beans">Beans</option>
You can also allow for the selection of more than one item by users, as in Example 11-8
Example 11-8 Using select with the multiple parameter
Vegetables <select name="veg" size="5" multiple="multiple">
<option value="Peas">Peas</option>
<option value="Beans">Beans</option>
<option value="Carrots">Carrots</option>
<option value="Cabbage">Cabbage</option>
<option value="Broccoli">Broccoli</option>
</select>
This HTML is not very different; only the size has been changed to “5” and the tag
multiple has been added But, as you can see from Figure 11-7, it is now possible to select more than one option by using the Ctrl key when clicking You can leave out the
size parameter if you wish, and the output will be the same, but with a larger list it
might take up too much screen space, so I recommend that you pick a suitable number
of rows and stick with it I also recommend against multiple select boxes smaller than two rows in height—some browsers may not correctly display the scroll bars needed
to access it
Figure 11-6 Creating a drop-down list with select
Trang 2You can also use the selected tag within a multiple select and can, in fact, have more
than one option preselected if you wish
Labels
You can provide an even better user experience by utilizing the label tag With it, you
can surround a form element, making it selectable by clicking any visible part contained
between the opening and closing label tags.
For instance, going back to the example of choosing a delivery time, you could allow
the user to click on the radio button itself and the associated text, like this:
<label>8am-Noon<input type="radio" name="time" value="1" /></label>
The text will not be underlined like a hyperlink when you do this, but as the mouse passes over, it will change to an arrow instead of a text cursor, indicating that the whole item is clickable
The submit button
To match the type of form being submitted, you can change the text of the submit
button to anything you like by using the value parameter, like this:
<input type="submit" value="Search" />
You can also replace the standard text button with a graphic image of your choice, using HTML such as this:
<input type="image" name="submit" src="image.gif" />
Sanitizing Input
Now we return to PHP programming It can never be emphasized enough that handling user data is a security minefield, and that it is essential to learn to treat all such data
Figure 11-7 Using a select with the multiple parameter
262 | Chapter 11: Form Handling
Trang 3with utmost caution from the word go It’s actually not that difficult to sanitize user input from potential hacking attempts, but it must be done
The first thing to remember is that regardless of what constraints you have placed in
an HTML form to limit the types and sizes of inputs, it is a trivial matter for a hacker
to use their browser’s View Source feature to extract the form and modify it to provide
malicious input to your website
Therefore you must never trust any variable that you fetch from either the $_GET or
$_POST arrays until you have processed it If you don’t, users may try to inject JavaScript into the data to interfere with your site’s operation, or even attempt to add MySQL commands to compromise your database
Therefore, instead of just using code such as the following when reading in user input:
$variable = $_POST['user_input'];
you should also use one or more of the following lines of code For example, to prevent escape characters being injected into a string that will be presented to MySQL, you should use the following (remembering that this function takes into account the current character set of a MySQL connection, so it can be used only with an open connection):
$variable = mysql_real_escape_string($variable);
To get rid of unwanted slashes, use:
$variable = stripslashes($variable);
And to remove any HTML from a string, use the following:
$variable = htmlentities($variable);
For example, this would change a string of interpretable HTML code like <b>hi</b> into <b>hi</b>, which displays as text, and won’t be interpreted as HTML tags
Finally, if you wish to strip HTML entirely from an input, use the following:
$variable = strip_tags($variable);
In fact, until you know exactly what sanitization you require for a program, Exam-ple 11-9 shows a pair of functions that bring all these checks together to provide a very good level of security
Example 11-9 The sanitizeString and sanitizeMySQL functions
<?php
function sanitizeString($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
Trang 4function sanitizeMySQL($var)
{
$var = mysql_real_escape_string($var);
$var = sanitizeString($var);
return $var;
}
?>
Add this code to the end of your PHP programs and you can then call it for each user input to sanitize, like this:
$variable = sanitizeString($_POST['user_input']);
Or, when you have an open MySQL connection:
$variable = sanitizeMySQL($_POST['user_input']);
An Example Program
So let’s look at how a real life PHP program integrates with an HTML form by creating
the program convert.php listed in Example 11-10 Type it in as shown and try it for yourself
Example 11-10 A program to convert values between Fahrenheit and Celsius
<?php // convert.php
$f = $c = "";
if (isset($_POST['f'])) $f = sanitizeString($_POST['f']);
if (isset($_POST['c'])) $c = sanitizeString($_POST['c']);
if ($f != '')
{
$c = intval((5 / 9) * ($f - 32));
$out = "$f °f equals $c °c";
}
elseif($c != '')
{
$f = intval((9 / 5) * $c + 32);
$out = "$c °c equals $f °f";
}
else $out = "";
echo <<<_END
<html><head><title>Temperature Converter</title>
</head><body><pre>
Enter either Fahrenheit or Celsius and click on Convert
<b>$out</b>
<form method="post" action="convert.php">
Fahrenheit <input type="text" name="f" size="7" />
Celsius <input type="text" name="c" size="7" />
<input type="submit" value="Convert" />
</form></pre></body></html>
264 | Chapter 11: Form Handling
Trang 5function sanitizeString($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
?>
When you call up convert.php in a browser, the result should look something like the
screenshot in Figure 11-8
Figure 11-8 The temperature conversion program in action
To break the program down, the first line initializes the variables $c and $f in case they
do not get posted to the program The next two lines fetch the values of either the field
named f or the one named c, for an input Fahrenheit or Celsius value If the user inputs
both, the Celsius is simply ignored and the Fahrenheit value is converted As a security measure, the new function sanitizeString from Example 11-9 is also used
So, having either submitted values or empty strings in both $f and $c, the next portion
of code constitutes an if elseif else structure that first tests whether $f has a value If not, it checks $c; otherwise, the variable $out is set to the empty string (more
on that in a moment)
If $f is found to have a value, the variable $c is assigned a simple mathematical expres-sion that converts the value of $f from Fahrenheit to Celsius The formula used is
Celsius = (5 / 9) × (Fahrenheit – 32) The variable $out is then set to a message string explaining the conversion
Trang 6On the other hand, if $c is found to have a value, a complementary operation is per-formed to convert the value of $c from Celsius to Fahrenheit and assign the result to
$f The formula used is Fahrenheit = (9 / 5) × (Celsius + 32) As with the previous section,
the string $out is then set to contain a message about the conversion
In both conversions, the PHP intval function is called to convert the result of the conversion to an integer value It’s not necessary, but looks better
With all the arithmetic done, the program now outputs the HTML, which starts with the basic head and title and then contains some introductory text before displaying the value of $out If no temperature conversion was made, $out will have a value of NULL and nothing will be displayed, which is exactly what we want when the form hasn’t yet been submitted But if a conversion was made, $out contains the result, which is displayed
After this, we come to the form, which is set to submit using the POST method to the
file convert.php (the program itself) Within the form, there are two inputs for either a
Fahrenheit or Celsius value to be entered A submit button with the text “Convert” is then displayed and the form is closed
After outputting the HTML to close the document, we come finally to the function sanitizeString from Example 11-9
All the examples in this chapter have used the POST method to send form
data I recommend this, as the neatest and most secure method
How-ever, the forms can easily be changed to use the GET method, as long as
values are fetched from the $_GET array instead of the $_POST array
Rea-sons to do this might include making the result of a search
bookmark-able or directly linkbookmark-able from another page.
The next chapter will show you how you can use the Smarty templating engine to provide a framework for separating your application code from the way your content
is presented to users
Test Your Knowledge: Questions
Question 11-1
Form data can be submitted using either the POST or the GET method Which asso-ciative arrays are used to pass this data to PHP?
Question 11-2
What is register_globals and why is it a bad idea?
Question 11-3
What is the difference between a text box and a text area?
266 | Chapter 11: Form Handling
Trang 7Question 11-4
If a form has to offer three choices to a user, each of which is mutually exclusive,
so that only one of the three can be selected, which input type would you use for this, given a choice between checkboxes and radio buttons?
Question 11-5
How can you submit a group of selections from a web form using a single field name?
Question 11-6
How can you submit a form field without displaying it in the browser?
Question 11-7
Which HTML tag is used to encapsulate a form element and support text or graphics, making the entire unit selectable with a mouse-click?
Question 11-8
Which PHP function converts HTML into a format that can be displayed but will not be interpreted as HTML by a browser?
See the section “Chapter 11 Answers” on page 444 in Appendix A for the answers to these questions
Trang 9CHAPTER 12
Templating with Smarty
As your projects grow more complicated, particularly when you start working with web designers, there’s likely to come a time when the convenience of separating the program code from the presentation becomes apparent
Initially PHP itself was developed as a sort of templating system with a few elements
of programming and flow control But it quickly developed into the powerful pro-gramming language we know today Some developers still treat it a little like a tem-plating system, though, as in the case of the WordPress blogging platform, which uses
a set of template PHP files for each theme
However, allowing presentation to become intertwined with programming can create problems, because it means that the layout designers have full access to the source code and can unwittingly make dangerous changes to it Additionally, using a separate tem-plating system frees up designers to modify templates to their hearts’ content, safe in the knowledge that nothing they do can break your program code; it leads to much greater flexibility
It’s also an incredible boon when your boss comes along and demands a whole load of design changes, because all you have to do is modify the template files Without a templating system, you’d very likely have to search through many files of PHP code to make the necessary modifications
Some programmers like to stick with just the programming language
when they develop web pages, and don’t use templates If you’re one of
them, I still recommend that you read this chapter, as you’ll learn all
about templating, in case you’re suddenly required to work on any
projects that use it.
Trang 10Why Smarty?
The Smarty templating system is probably the best known and most used on the In-ternet It provides the following benefits:
• Designers can’t break application code They can modify the templates all they want, but the code stays intact Consequently the code is tighter, more secure, and easier to maintain
• Errors in the templates are confined to Smarty’s error-handling routines, making them simple and intuitive to deal with
• With presentation in its own layer, designers can modify or completely redesign a web layout from scratch—all without intervention from the programmer
• Programmers can go about maintaining the application code, changing the way content is acquired, and so on, without disturbing the presentation layer
• Templates are a close representation of what the final output will be, which is an intuitive approach
• Smarty has many security features built in so that designers won’t breach security and you won’t open your server to the execution of arbitrary PHP code
But separating the application code from the presentation layer doesn’t mean that the logic is also separated, because Smarty offers comprehensive presentation logic fea-tures, too, as you’ll see later
Installation
To install Smarty, visit http://www.smarty.net/download.php and download the latest ZIP archive Once it’s downloaded, you need to perform the following steps:
1 Extract the contents of the downloaded file into a suitable folder
2 Determine your web server document’s root by running the following PHP snippet (if you don’t already know it):
<?php echo $_SERVER['DOCUMENT_ROOT']; ?>
3 Create a new folder called Smarty in this document root.
4 Open the extracted folder, navigate into the libs directory, and copy the entire contents (including subfolders) into the Smarty directory you just created You will
end up with the following directory structure in your document root:
Smarty
internals
(various files )
plugins
(various files )
Config_File.class.php
debug.tpl
270 | Chapter 12: Templating with Smarty