1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning PHP6, Apache, MySQL Web Development- P9 docx

30 311 0
Tài liệu đã được kiểm tra trùng lặp

Đ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

Thông tin cơ bản

Tiêu đề Manipulating and Creating Images with PHP
Trường học University of Example
Chuyên ngành Web Development
Thể loại Textbook
Năm xuất bản 2008
Thành phố Sample City
Định dạng
Số trang 30
Dung lượng 566,37 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Note that before you could merge the two images, you had to make the second image “ GD friendly ” by creating a duplicate copy.. The resource of the destination image $image in this exa

Trang 1

Chapter 7: Manipulating and Creating Images with PHP

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 imageheader(‘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

Trang 2

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

Trang 3

Chapter 7: Manipulating and Creating Images with PHP 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);

< h1 > Your image has been saved! < /h1 >

< img src=”images/ < ?php echo $_POST[‘id’]; ? > jpg” / >

/body >

< /html >

Trang 4

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.’);

//change this path to match your thumbnail directory

$thumbdir = $dir ‘/thumbs’;

//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” >

Trang 5

Chapter 7: Manipulating and Creating Images with PHP

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);

Trang 6

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?

Summar y

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

Trang 7

8

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

Trang 8

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

Trang 9

Chapter 8: Validating User Input

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:

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 = ‘’;

! #error { background-color: #600; border: 1px solid #FF0; color: #FFF;

text-align: center; margin: 10px; padding: 10px; } >

Trang 10

< 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 >

// populate the select options with the results

while ($row = mysql_fetch_assoc($result)) {

foreach ($row as $value) {

// populate the select options with years

Trang 11

Chapter 8: Validating User Input

FROM people WHERE people_isactor = 1 ORDER BY

people_fullname’;

$result = mysql_query($query, $db) or die(mysql_error($db));

// populate the select options with the resultswhile ($row = mysql_fetch_assoc($result)) { foreach ($row as $value) {

if ($row[‘people_id’] == $movie_leadactor) {

} else { echo ‘ < option value=”’ $row[‘people_id’] ‘” >

} echo $row[‘people_fullname’] ‘ < /option >

}}

? < /select > < /td >

< /tr > < tr >

< td > Director < /td >

< td > < select name=”movie_director” >

< ?php// select director records

$query = ‘SELECT people_id, people_fullname FROM

people WHERE people_isdirector = 1 ORDER BY

people_fullname’;

$result = mysql_query($query, $db) or die(mysql_error($db));

// populate the select options with the resultswhile ($row = mysql_fetch_assoc($result)) { foreach ($row as $value) {

if ($row[‘people_id’] == $movie_director) {

} else { echo ‘ < option value=”’ $row[‘people_id’] ‘” >

} echo $row[‘people_fullname’] ‘ < /option >

}}

? < /select > < /td >

< /tr > < tr >

< td colspan=”2” style=”text-align: center;” >

< ?php

if ($_GET[‘action’] == ‘edit’) {

Trang 12

echo ‘ < input type=”hidden” value=”’ $_GET[‘id’] ‘” name=”movie_id” / >

}

?

< input type=”submit” name=”submit”

value=” < ?php echo ucfirst($_GET[‘action’]); ? > ” / >

$db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or

die (‘Unable to connect Check your connection parameters.’);

Trang 13

Chapter 8: Validating User Input

trim($_POST[‘movie_director’]) : ‘’;

if (empty($movie_director)) { $error[] = urlencode(‘Please select a director.’);

}

if (empty($error)) { $query = ‘INSERT INTO movie

(movie_name, movie_year, movie_type, movie_leadactor, movie_director)

VALUES (“’ $movie_name ‘”, ‘ $movie_year ‘, ‘ $movie_type ‘, ‘ $movie_leadactor ‘, ‘ $movie_director ‘)’;

} else { header(‘Location:movie.php?action=add’ ‘ & error=’ join($error, urlencode(‘ < br/ > ’)));

} // Delete these lines $query = ‘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’] ‘)’;

// End deleted lines break;

} break;

case ‘edit’:

switch ($_GET[‘type’]) { case ‘movie’:

$error = array();

$movie_name = isset($_POST[‘movie_name’]) ? trim($_POST[‘movie_name’]) : ‘’;

if (empty($movie_name)) { $error[] = urlencode(‘Please enter a movie name.’);

} $movie_type = isset($_POST[‘movie_type’]) ? trim($_POST[‘movie_type’]) : ‘’;

if (empty($movie_type)) { $error[] = urlencode(‘Please select a movie type.’);

} $movie_year = isset($_POST[‘movie_year’]) ? trim($_POST[‘movie_year’]) : ‘’;

if (empty($movie_year)) { $error[] = urlencode(‘Please select a movie year.’);

} $movie_leadactor = isset($_POST[‘movie_leadactor’]) ?

Trang 14

‘ & error=’ join($error, urlencode(‘ < br/ > ’)));

Trang 15

Chapter 8: Validating User Input

3 Now open your browser and load admin.php , and then click the link to add a movie You will

be taken to the movie.php script you ’ ve just updated Try adding a movie with no name, and notice the error message stating the mistake made in filling in the form, as shown in Figure 8 - 1

Figure 8-1

How It Works

When the form passes information to the commit.php script, the data has to be verified In this case, you use a simple verification method: The isset() function returns true if the variable has been set, and false if not To ensure that the user did not submit the form with a blank field or a simple space

in the movie name field, you use trim() on the field ’ s content to eliminate any space leading or trailing the string and to compare the value to a null string (Some people like to trigger errors in web sites by entering erroneous input; don ’ t make their job easy.)

At the same time, if an error is detected, you add a message to the $error variable that collects all the error messages The error messages are URL encoded before being added because they will be passed

on the URL string They should be encoded to ensure that they will be passed back to the movie.php script correctly without being corrupted (See urlencode and 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.’);

}

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