Beginning PHP5, Apache, and MySQL Web Development split phần 4 pps

82 227 0
Beginning PHP5, Apache, and MySQL Web Development split phần 4 pps

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

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

2. Have a page on your site with funny photographs or cartoons and allow your users to write the caption for them. Place the text in a speech bubble that is appropriately sized based on the length of the caption they submit. 3. Create a page for kids where they can choose different heads, bodies, and tails from animals, and put them together to make a new creation and a new image. Or create a virtual paper doll site where kids can place different outfits on a model, then save the images they create. 226 Chapter 7 11_579665 ch07.qxd 12/30/04 8:05 PM Page 226 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 8 Validating User Input If you plan to accept user input on your site, you have to be prepared for mistakes. This could be simple human error, or a deliberate attempt to circumvent your Web forms. The most common human errors include basic typographical errors and format errors— failing to give a year in a date, for example. Deliberate errors could be a user who doesn’t want to provide his e-mail address, or it could be an attacker deliberately trying to corrupt your database with unexpected characters. No matter what the source, your script needs to be able to handle incorrect input, usu- ally by identifying the bad data and returning the user to the form page with an appropriate error message. This chapter covers user input validation, including: ❑ Validating simple string values ❑ Validating integer values ❑ Validating formatted text input Users Are Users Are Users . . . Consider an example: You work in a bank. You are developing a new system to allow the employ- ees to manage a customer account updating process on the company intranet. You use your well- known MM-DD-YYYY format for the date. It all works quite well when testing, but when put in production, your users say it doesn’t work. Why? Because all your company systems use the ISO 8601 YYYY-MM-DD date format (a standard used in many systems because the date can be sorted alphabetically). Your users are confused between the two different formats and input wrong infor- mation in the system. If the data is in the wrong format, you can end up with a corrupted database or trigger errors in your application. You can avoid this by using well-known formats and validating the user input. When you expect an integer value, for example, you can check that it is an integer before you try to use it. It’s a sim- ple enough rule, and you’ll learn how to do it later in this chapter. 12_579665 ch08.qxd 12/30/04 8:08 PM Page 227 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Incorporating Validation into the Movie Site To really understand the role of user input and validation, you need to see it in action. So, first you need to add a few fields to your beloved movie database. The modifications are all in the movie table. The movie application provides a lot of opportunities to check for user input. You will need to add a few features to the application, however, to provide more case studies. It will also help you to review what you learned in the previous chapters. Add a movie_release field INT(11) with default value 0 after the existing movie_year field, as shown in Figure 8-1. This allows you to store a timestamp for the movie release date. Then add a field named movie_rating at the end of the table type TINYINT (2). That information holds the movie rating you gave the movie when viewing it (see Figure 8-2). This rating goes from 0 to 10. Figure 8-1 228 Chapter 8 12_579665 ch08.qxd 12/30/04 8:08 PM Page 228 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 8-2 Forgot Something? Sometimes, when a user enters data in a form, he or she forgets to fill in a field. When this happens, the system has to react so that the insertion of the invalid or incomplete data will not corrupt the database. In some cases, these errors are made on purpose. In some cases, blank fields will appear first during searches and make the searching process harder than necessary; in other cases you will have erroneous statistics on your data (in your billing system, for example). In fact, these attempts to find cracks in the walls around your system are quite frequent. You need to design your system so it can react to such errors or malicious attempts to corrupt the database. Try It Out Adapting Your Script to the User Input In this exercise, you’ll be making sure that the script can adapt when the user fails to enter all the fields. 1. Copy the code you made in Chapter 6 into a new directory, open the movie.php script, and modify it as shown in the highlighted lines: 229 Validating User Input 12_579665 ch08.qxd 12/30/04 8:08 PM Page 229 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com <?php $link = mysql_connect(“localhost”, “bp5am”, “bp5ampass”) or die(“Could not connect: “ . mysql_error()); mysql_select_db(‘moviesite’, $link) or die ( mysql_error()); $peoplesql = “SELECT * FROM people”; $result = mysql_query($peoplesql) or die(“Invalid query: “ . mysql_error()); while ($row = mysql_fetch_array($result)) { $people[$row[‘people_id’]] = $row[‘people_fullname’]; } switch ($_GET[‘action’]) { case “edit”: $moviesql = “SELECT * FROM movie “ . “WHERE movie_id = ‘“ . $_GET[‘id’] . “‘“; $result = mysql_query($moviesql) or die(“Invalid query: “ . mysql_error()); $row = mysql_fetch_array($result); $movie_name = $row[‘movie_name’]; $movie_type = $row[‘movie_type’]; $movie_year = $row[‘movie_year’]; $movie_leadactor = $row[‘movie_leadactor’]; $movie_director = $row[‘movie_director’]; break; default: $movie_name = “”; $movie_type = “”; $movie_year = “”; $movie_leadactor = “”; $movie_director = “”; break; } ?> <html> <head> <title><?php echo $_GET[‘action’]; ?> movie</title> <style type=”text/css”> TD{color:#353535;font-family:verdana} TH{color:#FFFFFF;font-family:verdana;background-color:#336699} </style> </head> <body> <form action=”commit.php?action=<?php echo $_GET[‘action’]; ?>&type=movie&id=<?php if (isset($_GET[‘id’])) { echo $_GET[‘id’]; } ?>” method=”post”> <?php if (!empty($_GET[‘error’])) { echo “<div align=\”center\” “ . “style=\”color:#FFFFFF;background-color:#FF0000;” . 230 Chapter 8 12_579665 ch08.qxd 12/30/04 8:08 PM Page 230 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com “font-weight:bold\”>” . nl2br(urldecode($_GET[‘error’])) . “</div><br />”; } ?> <table border=”0” width=”750” cellspacing=”1” cellpadding=”3” bgcolor=”#353535” align=”center”> <tr> <td bgcolor=”#FFFFFF” width=”30%”>Movie Name</td> <td bgcolor=”#FFFFFF” width=”70%”> <input type=”text” name=”movie_name” value=”<?php echo $movie_name?>”> </td> </tr> <tr> <td bgcolor=”#FFFFFF”>Movie Type</td> <td bgcolor=”#FFFFFF”> <select id=”game” name=”movie_type” style=”width:150px”> <option value=”” selected>Select a type </option> <?php $sql = “SELECT movietype_id, movietype_label “ . “FROM movietype ORDER BY movietype_label”; $result = mysql_query($sql) or die(“<font color=\”#FF0000\”>Query Error</font>” . mysql_error()); while ($row = mysql_fetch_array($result)) { if ($row[‘movietype_id’] == $movie_type) { $selected = “ selected”; } else { $selected = “”; } echo ‘<option value=”’ . $row[‘movietype_id’] . ‘“‘ . $selected . ‘>’ . $row[‘movietype_label’] . “</option>\r\n”; } ?> </select> </td> </tr> <tr> <td bgcolor=”#FFFFFF”>Movie Year</td> <td bgcolor=”#FFFFFF”> <select name=”movie_year”> <option value=”” selected>Select a year </option> <?php for ($year=date(“Y”); $year >= 1970 ; $year ) { if ($year == $movie_year) { $selected = “ selected”; } else { $selected = “”; } ?> <option value=”<?php echo $year; ?>” <?php echo $selected; ?>><?php echo $year; ?></option> <?php } ?> 231 Validating User Input 12_579665 ch08.qxd 12/30/04 8:08 PM Page 231 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com </select> </td> </tr> <tr> <td bgcolor=”#FFFFFF”>Lead Actor</td> <td bgcolor=”#FFFFFF”> <select name=”movie_leadactor”> <option value=”” selected>Select an actor </option> <?php foreach ($people as $people_id => $people_fullname) { if ($people_id == $movie_leadactor) { $selected = “ selected”; } else { $selected = “”; } ?> <option value=”<?php echo $people_id; ?>” <?php echo $selected; ?>><?php echo $people_fullname; ?></option> <?php } ?> </select> </td> </tr> <tr> <td bgcolor=”#FFFFFF”>Director</td> <td bgcolor=”#FFFFFF”> <select name=”movie_director”> <option value=”” selected>Select a director </option> <?php foreach ($people as $people_id => $people_fullname) { if ($people_id == $movie_director) { $selected = “ selected”; } else { $selected = “”; } ?> <option value=”<?php echo $people_id; ?>” <?php echo $selected; ?>><?php echo $people_fullname; ?></option> <?php } ?> </select> </td> </tr> <tr> <td bgcolor=”#FFFFFF” colspan=”2” align=”center”> <input type=”submit” name=”submit” value=”<?php echo $_GET[‘action’]; ?>”> </td> </tr> </table> 232 Chapter 8 12_579665 ch08.qxd 12/30/04 8:08 PM Page 232 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com </form> </body> </html> 2. Save the file as movie.php and upload the new code to your work directory. 3. Open the commit.php script and modify it as shown in the highlighted lines: <?php // COMMIT ADD AND EDITS $error = ‘’; $link = mysql_connect(“localhost”, “bp5am”, “bp5ampass”) or die(“Could not connect: “ . mysql_error()); mysql_select_db(‘moviesite’, $link) or die ( mysql_error()); switch ($_GET[‘action’]) { case “edit”: switch ($_GET[‘type’]) { case “people”: $sql = “UPDATE people SET “ . “people_fullname = ‘“ . $_POST[‘people_fullname’] . “‘ WHERE people_id = ‘“ . $_GET[‘id’] . “‘“; break; case “movie”: $movie_name = trim($_POST[‘movie_name’]); if (empty($movie_name)) { $error .= “Please+enter+a+movie+name%21%0D%0A”; } if (empty($_POST[‘movie_type’])) { $error .= “Please+select+a+movie+type%21%0D%0A”; } if (empty($_POST[‘movie_year’])) { $error .= “Please+select+a+movie+year%21%0D%0A”; } if (empty($error)) { $sql = “UPDATE movie SET “ . “movie_name = ‘“ . $_POST[‘movie_name’] . “‘,” . “movie_year = ‘“ . $_POST[‘movie_year’] . “‘,” . “movie_type = ‘“ . $_POST[‘movie_type’] . “‘,” . “movie_leadactor = ‘“ . $_POST[‘movie_leadactor’] . “‘,” . “movie_director = ‘“ . $_POST[‘movie_director’] . “‘ “ . “WHERE movie_id = ‘“.$_GET[‘id’].”’”; } else { header(“location:movie.php?action=edit&error=” . $error . “&id=” . $_GET[‘id’] ); } break; } break; case “add”: switch ($_GET[‘type’]) { case “people”: $sql = “INSERT INTO people (people_fullname) “ . “VALUES (‘“ . $_POST[‘people_fullname’] . “‘)”; 233 Validating User Input 12_579665 ch08.qxd 12/30/04 8:08 PM Page 233 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com break; case “movie”: $movie_name = trim($_POST[‘movie_name’]); if (empty($movie_name)) { $error .= “Please+enter+a+movie+name%21%0D%0A”; } if (empty($_POST[‘movie_type’])) { $error .= “Please+select+a+movie+type%21%0D%0A”; } if (empty($_POST[‘movie_year’])) { $error .= “Please+select+a+movie+year%21%0D%0A”; } if (empty($error)) { $sql = “INSERT INTO movie (movie_name,movie_year,” . “movie_type,movie_leadactor,movie_director) “ . “VALUES (‘“ . $_POST[‘movie_name’] . “‘,” . “‘“ . $_POST[‘movie_year’] . “‘,” . “‘“ . $_POST[‘movie_type’] . “‘,” . “‘“ . $_POST[‘movie_leadactor’] . “‘,” . “‘“ . $_POST[‘movie_director’] . “‘)”; } else { header(“location:movie.php?action=add&error=” . $error); } break; } break; } if (isset($sql) && !empty($sql)) { echo “<! ”.$sql.” >”; $result = mysql_query($sql) or die(“Invalid query: “ . mysql_error()); ?> <p align=”center” style=”color:#FF0000”> Done. <a href=”index.php”>Index</a> </p> <?php } ?> 4. Save the file as commit.php and upload it to your server. 234 Chapter 8 12_579665 ch08.qxd 12/30/04 8:08 PM Page 234 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 5. Now open your browser and go to http://localhost/chapter8/index.php (adapt this URL to fit your setup) and try adding a movie with no name, as shown in Figure 8-3. Figure 8-3 235 Validating User Input 12_579665 ch08.qxd 12/30/04 8:08 PM Page 235 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... Merge and Split Unregistered Version - http://www.simpopdf.com 6 Now try to enter a new movie without setting the year and the movie type (see Figure 8 -4) Figure 8 -4 236 Validating User Input Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 7 Edit a movie from the index and try deleting the name and submitting the form (see Figure 8-5) Figure 8-5 237 Chapter 8 Simpo PDF Merge and. .. #ErrorDocument 40 4 /missing.html #ErrorDocument 40 4 “/cgi-bin/missing_handler.pl” #ErrorDocument 40 2 http://www.example.com/subscription_info.html 2 Change that information to the following, then restart Apache: # Customizable error responses come in three flavors: # 1) plain text 2) local redirects 3) external redirects # # Some examples: ErrorDocument 40 0 /error.php ?40 0 ErrorDocument 40 1 /error.php ?40 1 ErrorDocument... Beginning PHP5, Apache, MySQL Web Development 3 2 54 Open your browser and type http://localhost/asdf/qwerty/page.html, or any other page you know for certain doesn’t reside on your server, into the address bar You should see the “Page Not Found” message on the screen, similar to the message shown in Figure 9-1 Handling and Avoiding... /error.php ?40 1 ErrorDocument 40 3 /error.php ?40 3 ErrorDocument 40 4 /error.php ?40 4 ErrorDocument 500 /error.php?500 How It Works You have just edited Apache’s configuration file to help you with error handling By using the ErrorDocument directive, you are able to send users to specific error pages depending on what error the server has encountered For example, if you receive a 40 4 error, the typical “Page... like your Web site but still get the 252 Handling and Avoiding Errors Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com message through to the user that there has been a problem You can do that with any and all error messages that the server can encounter Many ErrorDocument codes exist, but we will focus on the error messages you see typically in everyday Web browsing: ❑ 40 0: Bad... know how to handle your errors and debug your own code Being able to efficiently and properly debug your code is an invaluable time-saver; and in Web development, $time == $money! Luckily, PHP comes with a full-featured Applications Programming Interface (API) that provides you with many ways to trap and resolve those unwanted errors PHP also allows you to use the API to capture the errors and create... “This is the custom error Page”; $error_output = “You should be here”; } ?> Beginning PHP5, Apache, MySQL Web Development 259 Chapter 9 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com How It Works The output that you see in the browser will be the same as you... header(“location:movie.php?action=add&error=” $error); } break; 245 Chapter 8 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com } break; } if (isset($sql) && !empty($sql)) { echo “”; $result = mysql_ query($sql) or die(“Invalid query: “ mysql_ error()); ?> Done Index 3 4 Now save the files, upload them, and open your browser to... people”; $result = mysql_ query($peoplesql) or die(“Invalid query: “ mysql_ error()); while ($row = mysql_ fetch_array($result)) { $people[$row[‘people_id’]] = $row[‘people_fullname’]; } switch ($_GET[‘action’]) { case “edit”: $moviesql = “SELECT * FROM movie “ “WHERE movie_id = ‘“ $_GET[‘id’] “‘“; $result = mysql_ query($moviesql) or die(“Invalid query: “ mysql_ error()); $row = mysql_ fetch_array($result);... Found” error or “Forbidden access” error pages and other requests of that sort) So, if someone visits your site, and he or she runs into the “Page Not Found” error page, Chapter 9 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com the script will e-mail the administrator and he or she can in turn check to see whether this was a valid request and there is something wrong with the page . href=”index.php”>Index</a> </p> <?php } ?> 4. Save the file as commit.php and upload it to your server. 2 34 Chapter 8 12_579665 ch08.qxd 12/30/ 04 8:08 PM Page 2 34 Simpo PDF Merge and Split Unregistered Version. $_GET[‘id’]); } break; } break; case “add”: switch ($_GET[‘type’]) { case “people”: 244 Chapter 8 12_579665 ch08.qxd 12/30/ 04 8:08 PM Page 244 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com $sql. 12/30/ 04 8:08 PM Page 235 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 6. Now try to enter a new movie without setting the year and the movie type (see Figure 8 -4) . Figure

Ngày đăng: 13/08/2014, 12:21

Từ khóa liên quan

Mục lục

  • Beginning PHP5, Apache, and MySQL Web Development

    • Cover

    • Contents

    • Part I: Getting Started

      • Chapter 1: Configuring Your Installation

        • Projects in This Book

        • Brief Intro to PHP, Apache, MySQL, and Open Source

          • A Brief History of Open Source Initiatives

          • Why Open Source Rocks

          • How the Pieces of the AMP Module Work Together

            • Apache

            • PHP

            • MySQL

            • AMP Installers

            • Foxserv

            • PHPTriad

            • XAMPP

            • Configuring Your Apache Installation

              • Testing Your Installation

              • Customizing Your Installation

              • Adding PHP to the Equation

              • Document Root

              • Configuring Your PHP Installation

                • Testing Your Installation

                • Customizing Your Installation

                • Configuring PHP5 to Use MySQL

                • Configuring Your MySQL Installation

                  • Testing Your Installation

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

  • Đang cập nhật ...

Tài liệu liên quan