Sams Teach Yourself Web Publishing with HTML and CSS in One Hour a Day (5th Edition) P74 docx

10 170 0
Sams Teach Yourself Web Publishing with HTML and CSS in One Hour a Day (5th Edition) P74 docx

Đang tải... (xem toàn văn)

Thông tin tài liệu

Processing Forms This code is a lot different from the old code I used to present the name field in the original listing in this example. First, I include an if statement that checks to see whether there's an error associated with this field. To do so, I use the array_key_exists() function, which is yet another built-in PHP function. Remember that the keys in $errors are the names of the fields with errors. So if the $errors array contains an element with the key name, it means that this field was not valid. If there is an error with the field, I include the attribute class="error" in the <label> tag for the field. When the form is presented, the label will be red, indicating to the user that he or she needs to fix that field, even if the user didn't bother to read the list of errors. If there isn't an error, the normal <label> tag is printed. Once that's done, I just have to print out the name field, but in this case I need to include the value that was submitted for the field if it's available. I include the value attribute in my <input> tag, and I use a short tag to include the value of $_POST['name'] as the value. Inside the expression evaluator, I've wrapped the variable containing the value for the field in the strip_tags() function. This PHP function automatically removes any HTML tags from a string, and it's used here to thwart any possible cross-site scripting attacks a malicious person might employ. The age field is identical to the name field in every way except its name, so I'll skip that and turn instead to the toys field. Here's the code: <p> <?php if (array_key_exists('toys', $errors)) { ?> <label for="toys[]" class="error"><b>Toys:</b></label> <?php } else { ?> <label for="toys[]"><b>Toys:</b></label> <?php } ?> <br /> <?php foreach ($toys as $key => $value) { ?> <input type="checkbox" name="toys[]" <?php if (in_array($key, $_POST['toys'])) { echo ?checked="checked" ?; } ?> value="<?= $key ?>" /> <?= $value?><br /> <?php } ?> </p> As you can see, the code for marking the label for the field as an error is the same for this field as it was for name. The more interesting section of the code here is the loop that creates the check boxes. When I was describing the form-processing section of the page, I explained that I put all the toys inside the array $toys so that I could print out the check boxes using a loop. There's the loop. The values in the <input> tags are the keys in the array, and the labels for the check boxes are the values. I use the associative array version of the foreach loop to copy each of the key/value pairs in the array into the variables $key and $value. Inside the loop, I print out the <input> tags, using toys[] as the parameter name to let PHP know that this field can have multiple values and should be treated as an array. To include the value for a field, I just use a short tag to insert the key into the value attribute of the tag. I use it again to print out the label for the check box, $value, after the tag. The last bit here is the if statement found within the <input> tag. Remember that if you want a check box to be prechecked when file:///G|/1/0672328860/ch20lev1sec7.html (8 von 11) [19.12.2006 13:50:17] Processing Forms a form is presented, you have to include the checked attribute. I use the in_array() function to check if the key currently being processed is in $_POST['toys']. If it is, I then print out the checked attribute using echo(). This ensures that all the items the user checked before submitting the form are still checked if validation fails. A browser displaying a form that contains some errors appears in Figure 20.2. Here's the full source listing for the page: Input <?php $toys = array('digicam' => 'Digital Camera', 'mp3' => 'MP3 Player', 'wlan' => 'Wireless LAN'); $errors = array(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { $errors = validate(); } function validate() { $errors = array(); if (empty($_POST['name'])) { $errors['name'] = 'You must enter your name.'; } if (!is_numeric($_POST['age'])) { $errors['age'] = "You must enter a valid age."; } if (empty($_POST['toys'])) { $errors['toys'] = 'You must choose at least one toy.'; } return $errors; } ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Registration Form</title> <style type="text/css"> label.error { color: red; } </style> </head> <body> <h1>Registration Form</h1> <p>Please fill out the form below to register for our site. Fields with bold labels are required.</p> <?php if (!empty($errors)) { ?> <ul> <?php foreach (array_values($errors) as $error) { ?> <li><?= $error ?></li> file:///G|/1/0672328860/ch20lev1sec7.html (9 von 11) [19.12.2006 13:50:17] Processing Forms <?php } ?> </ul> <?php } ?> <form method="post" action="<?= $_SERVER['PHP_SELF'] ?>"> <p> <?php if (array_key_exists('name', $errors)) { ?> <label for="name" class="error"><b>Name:</b></label> <?php } else { ?> <label for="name"><b>Name:</b></label> <?php } ?> <br /> <input name="name" value="<?= strip_tags($_POST['name']) ?>" /></p> <p> <?php if (array_key_exists('age', $errors)) { ?> <label for="age" class="error"><b>Age:</b></label> <?php } else { ?> <label for="age"><b>Age:</b></label> <?php } ?> <br /> <input name="age" value="<?= strip_tags($_POST['age']) ?>"/></p> <p> <?php if (array_key_exists('toys', $errors)) { ?> <label for="toys[]" class="error"><b>Toys:</b></label> <?php } else { ?> <label for="toys[]"><b>Toys:</b></label> <?php } ?> <br /> <?php foreach ($toys as $key => $value) { ?> <input type="checkbox" name="toys[]" <?php if (in_array($key, $_POST['toys'])) { echo 'checked="checked" '; } ?> value="<?= $key ?>" /> <?= $value?><br /> <?php } ?> </p> <p><input type="submit" value="register" /></p> </form> </body> </html> Output Figure 20.2. A form with some errors that were caught during validation. [View full size image] file:///G|/1/0672328860/ch20lev1sec7.html (10 von 11) [19.12.2006 13:50:17] Processing Forms file:///G|/1/0672328860/ch20lev1sec7.html (11 von 11) [19.12.2006 13:50:17] Using PHP Includes Using PHP Includes In the previous lesson, you learned how to use server-side includes, which enable you to easily include snippets of web pages within other web pages. PHP and all other serverside scripting languages provide the same functionality, generally with the added benefit of giving you a lot more control over how includes are applied. With PHP, files are included using built-in functions. You can conditionally include files, specify which file to include dynamically, or even nest include function calls within included pages. Here's a simple example of an include call: include("header.php"); On encountering that function call, PHP will try to read in and process a file named header.php in the same directory as the current page. If it can't find this file, it will try to find the file in each of the directories in its include path as well. The include path is a list of directories (generally specified by the server administrator) where PHP searches for files to include, and it's generally set for the entire server in a configuration file. Four include-related functions are built into PHP: require, require_once, include, and include_once. All these functions include an external file in the page being processed. The difference between "include" and "require" is how PHP reacts when the file being included isn't available. If include or include_once is used, the PHP page prints a warning and continues on. If require or require_once is used, an unavailable include file is treated as a fatal error and page processing stops. If you use require_once or include_once to include a file that was already included on the page, the function call will be ignored. If you use require or include, the file will be included no matter what. PHP includes are like HTML links in that you can use relative or absolute paths in your includes. The difference is that absolute PHP paths start at the root of file system rather than the web server's document root. So if you wanted to include a file using an absolute path on a computer running Windows, you'd write the include like this: require_once('c:\stuff\myfile.php'); That's almost never a good idea. You should always use relative paths where possible. In other words, if the included file is in the directory above the one where the including file is located, you should use a path like this: require_once(" /myinclude.php"); If the file being included is not stored with your other web documents, you should try to have that directory added to your server's include path rather than using absolute paths to access it. Caution Never pass data entered by a user to any include function; it's a big security risk. For example, this would be inappropriate: file:///G|/1/0672328860/ch20lev1sec8.html (1 von 3) [19.12.2006 13:50:17] Using PHP Includes require_once($_POST['file_to_include'); Choosing Which Include Function to Use Given these four very similar functions, how do you choose which makes the most sense to use? The most important factor in making that decision is the content of the file to be included. Generally there are two types of include filessnippets of markup that will be presented on your page, and PHP code libraries that provide code you are using on multiple pages throughout a site. If the file you are including is a library, you just about always want to use require_once. If you're using code from the library on a page, chances are the page will not work if the library file is not available, meaning that you should use require rather than include. If the file contains library code, you're not going to want to include it more than once. Let's look at an example. You've written a library called temperature_converter.php. The contents of the file are shown here: <?php function celsiusToFahrenheit($temp = 0) { return round(($temp * 9/5) + 32); } ?> This file contains one function, celsiusToFahrenheit(), which converts a Celsius temperature to Fahrenheit and then rounds the result so that the function returns an integer. Now let's look at a page that includes this file: <?php require_once("temperature_converter.php"); ?> <html> <head> <title>Current Temperature</title> </head> <body> <p>Current temperature in Fahrenheit: <?= celsiusToFahrenheit(55) ?></p> </body> </html> As you can see, in this case the page won't have any meaning if the function in the library page is not available, so using require makes sense. On this page, it wouldn't matter whether I used require or require_once because there are no other includes. Let's say that the page included another file, one that prints the current temperatures around the world. If that page also had a require() call for temperature_converter.php, the same code would be included twice. An error would cause the page to fail, because each function name can only be declared once. Using require_once ensures that your library code is available and that it is not accidentally included in your page multiple times. On the other hand, if you're including content that will be displayed within your page, then include or require make more sense. You don't have to worry about conflicts, and if you're including something to file:///G|/1/0672328860/ch20lev1sec8.html (2 von 3) [19.12.2006 13:50:17] Using PHP Includes be displayed on the page, chances are you want it to appear, even if you've already included the same thing. file:///G|/1/0672328860/ch20lev1sec8.html (3 von 3) [19.12.2006 13:50:17] Expanding Your Knowledge of PHP Expanding Your Knowledge of PHP PHP is a full-featured scripting language for creating web applications and even writing command-line scripts. What you've seen in this lesson is just a brief introduction to the language. There are more statements, lots more built-in functions, and plenty of other things about the application for which there isn't space to discuss in this lesson. Fortunately, an online version of the PHP manual is available that will fill in most of the blanks for you. You can find it at http://www.php.net/docs.php. Also, shelves of books about PHP are available to you. Some that you might want to look into are Sams Teach Yourself PHP in 24 Hours, 3rd Edition (ISBN 0672326191), Sams Teach Yourself PHP in 10 Minutes (ISBN 0672327627). You might also look at PHP and MySQL Web Development, 3rd Edition (ISBN 0672326728). There's more to PHP than just the core language, too. Lots of libraries have been written by users to take care of common programming tasks that you might run into. There's an online repository for these libraries called PEAR, which stands for PHP Extension and Application Repository. You can find it at http://pear.php.net/. For example, the eBay website provides an API (application programming interface) that you can use to integrate your own website with eBay. You could write the code to use this API yourself, but a library in PEAR already exists. You can find it at http://pear.php.net/package/Services_Ebay. This is just one of the many libraries you can obtain via PEAR. When you're writing your applications, make sure to check the PHP manual to ensure there's not already a built-in function to take care of whatever you're doing. If there isn't, you should check PEAR. As I said before, I left out huge swaths of PHP functionality in this lesson for the sake of space. Here are some areas that you'll want to look into before developing your own PHP applications. Database Connectivity I mentioned CRUD applications already. A CRUD application is generally just a front end for a relational database, which in turn is an application optimized for storing data within tables. Databases can be used to store content for websites, billing information for an online store, payroll for a company, or anything else that can be expressed as a table. It seems like there's a relational database providing the storage for just about every popular website. Because databases play such a huge role in developing web applications, PHP provides a lot of database- related functionality. Most relational databases are applications that can be accessed over a network, a lot like a web server. PHP is capable of connecting to every popular relational database. In order to communicate with relational databases, you have to use a language called SQLthe structured query language. That's another book unto itself. Regular Expressions Regular expressions comprise a small language designed to provide programmers with a flexible way to match patterns in strings. For example, the regular expression ^a.*z$ matches a string that starts with a, ends with z, and has some number of characters in between. You can use regular expressions to do much more fine-grained form validation than I did in Exercise 20.1. They're also used to extract information from files, search and replace within strings, parse email addresses, or anything else that requires you to solve a problem with pattern matching. Regular expressions are incredibly flexible, but file:///G|/1/0672328860/ch20lev1sec9.html (1 von 2) [19.12.2006 13:50:18] Expanding Your Knowledge of PHP the syntax can be a bit complex. PHP actually supports two different varieties of regular expression syntaxPerl style and POSIX style. You can read about both of them in the PHP manual. Sending Mail PHP provides functions for sending email. For example, you could write a PHP script that automatically notifies an administrator by email when a user registers for a website, or sends users a password reminder if they request one when they forget their password. PHP also provides functions that enable your applications to retrieve mail as well as send it, making it possible to write web-based email clients and other such applications. Object-Oriented PHP PHP provides features for object-oriented development if you prefer that style of programming. The object-oriented features work differently between PHP 4, which is the version that's most commonly deployed, and PHP 5, the most recent version of the language. For more information on object-oriented PHP, refer to the manual. Cookies and Sessions Cookies are a browser feature that lets websites set values that are stored by your browser and returned to the server any time you request a page. For example, when users log into your site, you can set a cookie on their computers to keep track of who they are so that you don't have to force them to log in any time they want to see a passwordprotected page. You can also use cookies to keep track of when visitors return to your site after their initial visit. PHP provides full support for cookies. It also provides a facility called sessions. Sessions enable you to store data between requests to the server. For example, you could read a user's profile into his or her session when that user logs into the site, and then reference it on every page without going back and loading it all over again. Generally cookies are used with sessions so that the server can keep track of which session is associated with a particular user. File Uploads Back in Lesson 10, you learned about file upload fields for forms. PHP can deal with file uploads, enabling the programmer to access and manipulate them. With PHP, file uploads are stored to a temporary location on the server, and it's up to the programmer to decide whether to store them permanently and, if so, where to put them. file:///G|/1/0672328860/ch20lev1sec9.html (2 von 2) [19.12.2006 13:50:18] Summary Summary This lesson provided a whirlwind tour of the PHP language, and it explained how serverside scripts are written in general. Although the syntax of other languages will differ from PHP, the basic principles for dealing with user input, processing forms, and embedding scripts in your pages will be quite similar. In the next lesson, you'll learn how to take advantage of applications that other people have written rather than writing them yourself. Just as PHP has lots of built-in functions to take care of common tasks, so too are there many popular applications that you can download and install rather than writing them from scratch yourself. file:///G|/1/0672328860/ch20lev1sec10.html [19.12.2006 13:50:18] . there's a relational database providing the storage for just about every popular website. Because databases play such a huge role in developing web applications, PHP provides a lot of database- related. storing data within tables. Databases can be used to store content for websites, billing information for an online store, payroll for a company, or anything else that can be expressed as a table database- related functionality. Most relational databases are applications that can be accessed over a network, a lot like a web server. PHP is capable of connecting to every popular relational database.

Ngày đăng: 07/07/2014, 09:20

Tài liệu cùng người dùng

Tài liệu liên quan