Beginning PHP6, Apache, MySQL Web Development- P9 docx

30 311 0
Beginning PHP6, Apache, MySQL Web Development- P9 docx

Đ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

Chapter 7: Manipulating and Creating Images with PHP 211 2. Add the following line to your image_effect.php file, as before: // add the caption if requested if (isset($_GET[‘capt’])) { imagettftext($image, 12, 0, 20, 20, 0, $font, $_GET[‘capt’]); } //add the logo watermark if requested if (isset($_GET[‘logo’])) { // determine x and y position to center watermark list($width, $height) = getimagesize($dir . ‘/’ . $_GET[‘id’] . ‘.jpg’); list($wmk_width, $wmk_height) = getimagesize(‘images/logo.png’); $x = ($width - $wmk_width) / 2; $y = ($height - $wmk_height) / 2; $wmk = imagecreatefrompng(‘images/logo.png’); imagecopymerge($image, $wmk, $x, $y, 0, 0, $wmk_width, $wmk_height, 20); imagedestroy($wmk); } // show the image header(‘Content-Type: image/jpeg’); imagejpeg($image, ‘’, 100); ? > 3. Go ahead and try it out! Your screen should resemble that in Figure 7 - 9 . Figure 7-9 c07.indd 211c07.indd 211 12/10/08 6:01:22 PM12/10/08 6:01:22 PM Part I: Movie Review Web Site 212 How It Works You have simply added another option for your users, and you did it using the imagecopymerge() function. Note that before you could merge the two images, you had to make the second image “ GD friendly ” by creating a duplicate copy. Because your image was a PNG image, you used the imagecreatefrompng() function. The nine arguments for the imagecopymerge() function are as follows, in this order: 1. The resource of the destination image ( $image in this example, since the $image file is the one you are making all the changes to and the one that will be shown at the end of your script) . 2. The resource of the second image, or source image ( $wmk in this example) . 3. The x - coordinate on the destination image (0 represents the leftmost boundary) . 4. The y - coordinate on the destination image (0 represents the uppermost boundary) . 5. The x - coordinate on the second image to start copying from (0 in this example, because you want the whole image) . 6. The y - coordinate on the second image to start copying from (0 in this example, because you want the whole image) . 7. The width of the portion of the second image to be merged ( $wmk_width in this example, representing as much of the second image as will fit on the destination image) . 8. The height of the portion of the second image to be merged ( $wmk_height in this example, representing as much of the second image as will fit on the destination image) . 9. The percent of transparency of the two images to be merged, with 100 being equal to the second image completely opaque, and 0 completely transparent . We hope you ’ re still with us, because there is one more thing we would like to do. Creating Thumbnails Of course, showing your users ’ images at full size is fine, if they want to see them up close. However, that format is not too conducive to showing a photo gallery or list of many photos on a page. This section discusses how you can automatically create a thumbnail of each of your uploaded files that will be used for just that purpose — a photo gallery of all your photos. c07.indd 212c07.indd 212 12/10/08 6:01:23 PM12/10/08 6:01:23 PM Chapter 7: Manipulating and Creating Images with PHP 213 Try It Out Creating Thumbnails You want to automatically create a thumbnail version of all the images that are uploaded by the users, so you will be modifying check_image.php and including this function. 1. Create a subdirectory of your images folder to house the thumbnails. For this example, we created C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\ images\thumbs . Make sure your directory has write permissions. 2. Modify your check_image.php file by adding the two new sections of code that follow: //change this path to match your images directory $dir =’C:/Program Files/Apache Software Foundation/Apache2.2/htdocs/images’; //change this path to match your thumbnail directory $thumbdir = $dir . ‘/thumbs’; // save the image with the filter applied imagejpeg($image, $dir . ‘/’ . $_POST[‘id’] . ‘.jpg’, 100); //set the dimensions for the thumbnail $thumb_width = $width * 0.10; $thumb_height = $height * 0.10; //create the thumbnail $thumb = imagecreatetruecolor($thumb_width, $thumb_height); imagecopyresampled($thumb, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height); imagejpeg($thumb, $dir . ‘/’ . $_POST[‘id’] . ‘.jpg’, 100); imagedestroy($thumb); ? > < html > < head > < title > Here is your pic! < /title > < /head > < body > < h1 > Your image has been saved! < /h1 > < img src=”images/ < ?php echo $_POST[‘id’]; ? > .jpg” / > < /body > < /html > c07.indd 213c07.indd 213 12/10/08 6:01:23 PM12/10/08 6:01:23 PM Part I: Movie Review Web Site 214 3. Now you ’ re going to create gallery.php , which will act as your photo gallery to display the thumbnail images. Type the following in your editor: < ?php //connect to MySQL $db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_select_db(‘moviesite’, $db) or die(mysql_error($db)); //change this path to match your images directory $dir =’images’; //change this path to match your thumbnail directory $thumbdir = $dir . ‘/thumbs’; ? > < html > < head > < title > Welcome to our Photo Gallery < /title > < style type=”text/css” > th { background-color: #999;} .odd_row { background-color: #EEE; } .even_row { background-color: #FFF; } < /style > < /head > < body > < p > Click on any image to see it full sized. < /p > < table style=”width:100%;” > < tr > < th > Image < /th > < th > Caption < /th > < th > Uploaded By < /th > < th > Date Uploaded < /th > < /tr > < ?php //get the thumbs $result = mysql_query(‘SELECT * FROM images’) or die(mysql_error()); $odd = true; while ($rows = mysql_fetch_array($result)) { echo ($odd == true) ? ‘ < tr class=”odd_row” > ’ : ‘ < tr class=”even_row” > ’; $odd = !$odd; extract($rows); echo ‘ < td > < a href=”’ . $dir . ‘/’ . $image_id . ‘.jpg” > ’; echo ‘ < img src=”’ . $thumbdir . ‘/’ . $image_id . ‘.jpg” > ’; echo ‘ < /a > < /td > ’; echo ‘ < td > ’ . $image_caption . ‘ < /td > ’; echo ‘ < td > ’ . $image_username . ‘ < /td > ’; echo ‘ < td > ’ . $image_date . ‘ < /td > ’; echo ‘ < /tr > ’; } ? > < /table > < /body > < /html > c07.indd 214c07.indd 214 12/10/08 6:01:23 PM12/10/08 6:01:23 PM Chapter 7: Manipulating and Creating Images with PHP 215 4. Now upload some images, using your upload_image.html page. When you have a few, go to gallery.php in your browser and see what you have. Your screen should look something like Figure 7 - 10 . Figure 7-10 Ok, so it ’ s not pretty, and it ’ s mostly utilitarian in appearance. The important thing is that it works! You can add the bells and whistles later; we just want to make sure you can make a thumbnail. How It Works The actual thumbnail itself is created in your check_image.php file, so let ’ s take a look at that first. You first give your thumbnail its own directory, and you ’ re using the same naming scheme, for simplicity ’ s sake. Then the following lines complete the task of making the thumbnail for you: //set the dimensions for the thumbnail $thumb_width = $width * 0.10; $thumb_height = $height * 0.10; //create the thumbnail $thumb = imagecreatetruecolor($thumb_width, $thumb_height); imagecopyresampled($thumb, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height); imagejpeg($thumb, $dir . ‘/’ . $_POST[‘id’] . ‘.jpg’, 100); imagedestroy($thumb); c07.indd 215c07.indd 215 12/10/08 6:01:23 PM12/10/08 6:01:23 PM Part I: Movie Review Web Site 216 The size of the thumbnails is set equal to 10% of the size of the original picture. By using percentages instead of hard integers, you ensure that the proportions are kept equal and no skewing of your image occurs. Of course, you can make this smaller or larger depending on your users ’ preferences and the typical dimensions of the file uploads. Or you can do some math to determine appropriate hard integers based on the percentages and a maximum ceiling value. We just kept it simple. The process then creates a blank image in memory based on the smaller dimensions for the thumbnail and copies the source image onto it. The newly created thumbnail is then saved in the proper location, with the same name as the full - size image. Easy as pie, right? Summary This chapter covered a lot, and yet it only scratches the surface of image manipulation using the GD extension. You have seen how you can upload images, resize them, change their coloring, create an automatic thumbnail, create new images, and merge two images together. You used a form to get the image from the user and implemented appropriate checks to make sure the uploaded file was indeed an image of the correct format. Not all forms are so straightforward to check, though. In the next chapter, you ’ ll learn how to check that users enter information in your form in the proper format, and how to give them appropriate feedback when they don ’ t. Exercises 1. Create a site called “ A Virtual Vacation. ” Offer different backgrounds that people can superim- pose photos of themselves on, and let them send virtual postcards to their friends and family. 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 and then save the images they create. c07.indd 216c07.indd 216 12/10/08 6:01:24 PM12/10/08 6:01:24 PM 8 Validating User Input If you plan to accept user input on your site, you have to be prepared for mistakes. Incorrect input could be simple human error or a deliberate attempt to circumvent the purpose (or security) of your web application. The most common human errors include basic typographical errors and format errors — such as showing a year as two digits when a full four - digit year was requested or needed. Erroneous input sent deliberately could be from a user who doesn ’ t want to provide his or her e - mail address, or from an attacker intentionally trying to corrupt your database with polluted values. No matter what the source, your script needs to be able to handle incorrect input. There are many ways to do so, but perhaps the most popular is to identify the bad data and return the user to the form 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 . . . Let ’ s start by considering this example: You work in a bank. You are developing a new system to allow the employees to start the workflow of updating customer account information 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 it ’ s put in production, your users say it doesn ’ t work. Why? Because all your banking 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 information to 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 simple enough rule, and you ’ ll learn how to do it later in this chapter. ❑ ❑ ❑ c08.indd 217c08.indd 217 12/10/08 5:48:12 PM12/10/08 5:48:12 PM 218 Part I: Movie Review Web Site 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 the movie table in your beloved movie database. 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. Try It Out Adapting Your Script to the User Input You must first add two new columns to the movie table. You ’ ve done this several times already, so it should be a simple process. 1. Open a text editor, and enter this code: < ?php $db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_select_db(‘moviesite’, $db) or die(mysql_error($db)); //alter the movie table to include release and rating $query = ‘ALTER TABLE movie ADD COLUMN ( movie_release INTEGER UNSIGNED DEFAULT 0, movie_rating TINYINT UNSIGNED DEFAULT 5)’; mysql_query($query, $db) or die(mysql_error($db)); echo ‘Movie database successfully updated!’; ? > 2. Save the file as db_ch08.php . 3. Open the page in your web browser. You should see the message “ Movie database successfully updated! ” How It Works You ’ ve added two fields — movie_release and movie_rating — at the end of the movies table. The movie_release field allows you to store a timestamp for the movie ’ s release date. The movie_ rating field allows you to give the movie a rating when viewing it. If this rating goes from 0 to 10, then 5 would be a neutral rating. 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. An attacker may try to inject erroneous tracking information to corrupt your statistics, or attempt to try to find holes in your application. This is more c08.indd 218c08.indd 218 12/10/08 5:48:12 PM12/10/08 5:48:12 PM Chapter 8: Validating User Input 219 common than you may think, so it is very important to design and test your system so it can react to such errors — whether benign or malicious — to protect your data. Try It Out Adapting Your Script to the User Input In this exercise, you ’ ll be making sure that the script can react appropriately when the user fails to enter data in all the fields. 1. Open the code file movie.php you wrote in Chapter 6, and modify it as shown in the highlighted lines: < ?php $db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_select_db(‘moviesite’, $db) or die(mysql_error($db)); if ($_GET[‘action’] == ‘edit’) { //retrieve the record’s information $query = ‘SELECT movie_name, movie_type, movie_year, movie_leadactor, movie_ director FROM movie WHERE movie_id = ‘ . $_GET[‘id’]; $result = mysql_query($query, $db) or die(mysql_error($db)); extract(mysql_fetch_assoc($result)); } else { //set values to blank $movie_name = ‘’; $movie_type = 0; $movie_year = date(‘Y’); $movie_leadactor = 0; $movie_director = 0; } ? > < html > < head > < title > < ?php echo ucfirst($_GET[‘action’]); ? > Movie < /title > < style type=”text/css” > < ! #error { background-color: #600; border: 1px solid #FF0; color: #FFF; text-align: center; margin: 10px; padding: 10px; } > < /style > < /head > < body > < ?php if (isset($_GET[‘error’]) & & $_GET[‘error’] != ‘’) { echo ‘ < div id=”error” > ’ . $_GET[‘error’] . ‘ < /div > ’; } ? > c08.indd 219c08.indd 219 12/10/08 5:48:12 PM12/10/08 5:48:12 PM 220 Part I: Movie Review Web Site < form action=”commit.php?action= < ?php echo $_GET[‘action’]; ? > & type=movie” method=”post” > < table > < tr > < td > Movie Name < /td > < td > < input type=”text” name=”movie_name” value=” < ?php echo $movie_name; ? > ”/ > < /td > < /tr > < tr > < td > Movie Type < /td > < td > < select name=”movie_type” > < ?php // select the movie type information $query = ‘SELECT movietype_id, movietype_label FROM movietype ORDER BY movietype_label’; $result = mysql_query($query, $db) or die(mysql_error($db)); // populate the select options with the results while ($row = mysql_fetch_assoc($result)) { foreach ($row as $value) { if ($row[‘movietype_id’] == $movie_type) { echo ‘ < option value=”’ . $row[‘movietype_id’] . ‘” selected=”selected” > ’; } else { echo ‘ < option value=”’ . $row[‘movietype_id’] . ‘” > ’; } echo $row[‘movietype_label’] . ‘ < /option > ’; } } ? > < /select > < /td > < /tr > < tr > < td > Movie Year < /td > < td > < select name=”movie_year” > < ?php // populate the select options with years for ($yr = date(“Y”); $yr > = 1970; $yr ) { if ($yr == $movie_year) { echo ‘ < option value=”’ . $yr . ‘” selected=”selected” > ’ . $yr . ‘ < /option > ’; } else { echo ‘ < option value=”’ . $yr . ‘” > ’ . $yr . ‘ < /option > ’; } } ? > < /select > < /td > < /tr > < tr > < td > Lead Actor < /td > < td > < select name=”movie_leadactor” > < ?php // select actor records $query = ‘SELECT people_id, people_fullname c08.indd 220c08.indd 220 12/10/08 5:48:13 PM12/10/08 5:48:13 PM [...]... Figure 8-2 229 c08.indd 229 12/10/08 5:48:15 PM Part I: Movie Review Web Site Figure 8-2 3 Now open commit.php, and modify it as follows (modifications are highlighted): Commit Done! 224 c08.indd 224 12/10/08 5:48:14 PM Chapter 8: Validating User Input 3 Now open... urldecode functions in the manual; for more information, check the PHP web site at www.php.net/url.) $error = array(); $movie_name = (isset($_POST[‘movie_name’]) ? trim($_POST[‘movie_name’]) : ‘’; if (empty($movie_name)) { $error[] = urlencode(‘Please enter a movie name.’); } 225 c08.indd 225 12/10/08 5:48:14 PM Part I: Movie Review Web Site Once you are sure that an error has occurred, you redirect the . ?php //connect to MySQL $db = mysql_ connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_ select_db(‘moviesite’, $db) or die (mysql_ error($db)); . < /tr > < ?php //get the thumbs $result = mysql_ query(‘SELECT * FROM images’) or die (mysql_ error()); $odd = true; while ($rows = mysql_ fetch_array($result)) { echo ($odd == true). < ?php $db = mysql_ connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_ select_db(‘moviesite’, $db) or die (mysql_ error($db));

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

Mục lục

  • cover.pdf

  • page_c1.pdf

  • page_r01.pdf

  • page_r02.pdf

  • page_r03.pdf

  • page_r04.pdf

  • page_r05.pdf

  • page_r06.pdf

  • page_r07.pdf

  • page_r08.pdf

  • page_r09.pdf

  • page_r10.pdf

  • page_r11.pdf

  • page_r12.pdf

  • page_r13.pdf

  • page_r14.pdf

  • page_r15.pdf

  • page_r16.pdf

  • page_r17.pdf

  • page_r18.pdf

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

Tài liệu liên quan