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

Practical PHP and MySQLBuilding Eight Dynamic Web Applications phần 6 potx

52 441 0

Đ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

Định dạng
Số trang 52
Dung lượng 6,65 MB

Nội dung

247 CHAPTER 7 Building an Online Auction Site $db = mysql_connect($dbhost, $dbuser, $dbpassword); mysql_select_db($dbdatabase, $db); After this initial code, protect the page from people who are not logged in. Use the usual trick of checking to see if a USERNAME session variable exists: $db = mysql_connect($dbhost, $dbuser, $dbpassword); mysql_select_db($dbdatabase, $db); if(isset($_SESSION[‘USERNAME’]) == FALSE) { header(“Location: “ . $config_basedir . “/login.php?ref=newitem”); } Begin processing the form: if(isset($_SESSION[‘USERNAME’]) == FALSE) { header(“Location: “ . $config_basedir . “/login.php?ref=newitem”); } if($_POST[‘submit’]) { $validdate = checkdate($_POST[‘month’], $_POST[‘day’], $_POST[‘year’]); After you check to see if the Submit button has been clicked, you use a spe- cial function called checkdate(). This PHP function is passed a month, day, and year in numbers and determines whether the combination of values is a valid date. This function is useful for determining invalid dates such as Febru- ary 31, 2005. In this new line of code, the variables from the form are passed to the function. If the date is valid, the function returns TRUE; if not, the function returns FALSE. Next, you check the result of the function and act accordingly. First, check to see if the date is valid: if($_POST[‘submit’]) { $validdate = checkdate($_POST[‘month’], $_POST[‘day’], $_POST[‘year’]); if($validdate == TRUE) { $concatdate = $_POST[‘year’] . “-” . sprintf(“%02d”, $_POST[‘day’]) . “-” . sprintf(“%02d”, $_POST[‘month’]) . “ “ . $_POST[‘hour’] . “:” . $_POST[‘minute’] . “:00”; If the date is valid, the numbers are concatenated to form a valid MySQL date. MySQL dates come in the form 0000-00-00 00:00 (year, month, day, hour, minute). Imagine that the user selected 10 as the day, 12 as the month, 2005 as the year, 11 248 Practical PHP and MySQL as the hour, and 30 as the minute. With these numbers, the valid date would be 2005-12-10 11:30. The sprintf() function (which you used earlier to pad prices with zeros) was used again, this time to ensure that single digits have a leading zero (so 1 would become 01 and so on). This is important for the date to be a valid MySQL date. Construct the query to insert the data: $concatdate = $_POST[‘year’] . “-” . sprintf(“%02d”, $_POST[‘day’]) . “-” . sprintf(“%02d”, $_POST[‘month’]) . “ “ . $_POST[‘hour’] . “:” . $_POST[‘minute’] . “:00”; $itemsql = “INSERT INTO items(user_id, cat_id, name, startingprice, description, dateends) VALUES(“ . $_SESSION[‘USERID’] . “, “ . $_POST[‘cat’] . “, ‘“ . addslashes($_POST[‘name’]) . “‘, “ . $_POST[‘price’] . “, ‘“ . addslashes($_POST[‘description’]) . “‘, ‘“ . $concatdate . “‘);”; mysql_query($itemsql); $itemid = mysql_insert_id(); header(“Location: “ . $config_basedir . “/addimages.php?id=” . $itemid); } Within the query, a new function called addslashes() was wrapped around the boxes that accept input in the form of letters. This helps to prevent input errors. Finally, a header redirect jumps to the addimages.php page and passes it a GET variable, called id, with the insert id. Earlier in the code, you made a check to see if the date was valid. If the date was invalid, reload the page and pass the error flag: header(“Location: “ . $config_basedir . “/addimages.php?id=” . $itemid); } else { header(“Location: “ . $config_basedir . “/newitem.php?error=date”); } } 249 CHAPTER 7 Building an Online Auction Site NOTE The Risks with Input When you accept any kind of input from a user, there is a risk that the input could break the query. The most common breakage occurs when a user types a single quotation mark, because the quotation mark ends the input and anything after the second quotation mark is ignored. Imagine that the user types ‘Tim O’Chin’. The query would be as follows: INSERT INTO users(name) VALUES(‘Tim O’Chin’); In this query, the second quotation mark (in O’Chin) ends the input and causes a SQL error. In your projects, it is unlikely that you have encountered this error. This is because a feature called magic_quotes is likely to be turned on in your php.ini file. With this feature, any quotation marks accepted from a form are automatically escaped. The act of escaping a quotation mark happens when you use a forward slash to make the quotation mark legitimate. As such, a properly escaped query would be: INSERT INTO users(name) VALUES(‘Tim O\’Chin’); You can run this project with magic_quotes turned off if you wrap your data withaddslashes(); this function escapes the quotation marks. After closing the main if block, begin the else that displays the form: } } else { require(“header.php”); ?> <h1>Add a new item</h1> <strong>Step 1</strong> - Add your item details. After the form, add the closing curly bracket and footer code: </table> </form> <?php } require(“footer.php”); ?> 250 Practical PHP and MySQL Adding the Images Being able to upload images is a common and useful skill used when developing Web sites. The basic technique is as follows: 1. Provide a form the user can use to select an image. 2. When the user clicks the Submit button, transfer the image to a temporary location on the server. Inside this location, give the file a random, temporary filename. 3. Check that the image is valid and copy it to a specific directory on the Web server. 4. Add the name of the image and the id of the item it is associated with to the images table. With this process complete, you can iterate through the images table for items with the same id and then add the filename to the image HTML tag from the table. Create a new file called addimages.php and add the following form: <form enctype=”multipart/form-data” action=”<?php pf_script_with_get($SCRIPT_NAME); ?>” method=”POST”> <input type=”hidden” name=”MAX_FILE_SIZE” value=”3000000”> <table> <tr> <td>Image to upload</td> <td><input name=”userfile” type=”file”></td> </tr> <tr> <td colspan=”2”><input type=”submit” name=”submit” value=”Upload File”></td> </tr> </table> </form> When you have finished adding photos, go and <a href=”<?php echo “itemdetails.php?id=” . $validid; ?>”>see your item</a>! Within the form tag, you created a new attribute, called enctype, that ensures the form submits the image data in an understandable format. The first <input> tag creates a special hidden form element that can be used to store hidden information and variables in the form. In this example, the hidden element stores the maximum size of the image. The second input element is a userfile type and adds a browse button that the user can click to select the image to upload. The preceding code also adds a Submit button. 251 CHAPTER 7 Building an Online Auction Site Jump to the beginning of the page (before the form) and start adding the code to process the form: <?php session_start(); include(“config.php”); include(“functions.php”); $db = mysql_connect($dbhost, $dbuser, $dbpassword); mysql_select_db($dbdatabase, $db); $validid = pf_validate_number($_GET[‘id’], “redirect”, “index.php”); After the usual introductory code, protect the page from users who are not logged in: $validid = pf_validate_number($_GET[‘id’], “redirect”, “index.php”); if(isset($_SESSION[‘USERNAME’]) == FALSE) { header(“Location: “ . $HOST_NAME . “login.php?ref=images&id=” . $validid); } Select the user_id from the items table for the current item. This is required so you can check that the owner of the item—not a random user—is accessing the page. if(isset($_SESSION[‘USERNAME’]) == FALSE) { header(“Location: “ . $HOST_NAME . “login.php?ref=images&id=” . $validid); } $theitemsql = “SELECT user_id FROM items WHERE id = “ . $validid . “;”; $theitemresult = mysql_query($theitemsql); $theitemrow = mysql_fetch_assoc($theitemresult); Check if the current user owns the item by checking if the data from the query matches the USERID session variable. If not, redirect the user: $theitemresult = mysql_query($theitemsql); $theitemrow = mysql_fetch_assoc($theitemresult); if($theitemrow[‘user_id’] != $_SESSION[‘USERID’]) { header(“Location: “ . $config_basedir); } To process the form, you use a new PHP superglobal called $_FILES, which you can used to access uploaded files. When a file is uploaded, it contains a number of different attributes, such as the file name, size, type, and so on. 252 Practical PHP and MySQL NOTE Poking at $_FILES If you want to see what is in the $_FILES array, or any other variable or array for that matter, use print_r(): print_r($_FILES); To access specific information from a specific array, use the following format: $_FILES[‘array’][‘item’] For example, you could refer to the filename of the file in the userfile box that you added by using: $_FILES[‘userfile’][‘name’] Before the file is authorized, you will run the file through a series of validation checks to ensure that a file was actually uploaded, that it is a legitimate photo, and that the size is not too large. First, check that a file was uploaded: if($theitemrow[‘user_id’] != $_SESSION[‘USERID’]) { header(“Location: “ . $config_basedir); } if($_POST[‘submit’]) { if($_FILES[‘userfile’][‘name’] == ‘’) { header(“Location: “ . $HOST_NAME . $SCRIPT_NAME . “?error=nophoto”); } This code checks to see if the name information in the $_FILES array has a value. If it does not, the page reloads with an appended error variable. Now you can run a further set of tests. First, check to see if the size is legitimate (not zero): header(“Location: “ . $HOST_NAME . $SCRIPT_NAME . “?error=nophoto”); } elseif($_FILES[‘userfile’][‘size’] == 0) { header(“Location: “ . $HOST_NAME . $SCRIPT_NAME . “?error=photoprob”); } 253 CHAPTER 7 Building an Online Auction Site Check that the size is not greater than the maximum file size set in the hidden field: header(“Location: “ . $HOST_NAME . $SCRIPT_NAME . “?error=photoprob”); } elseif($_FILES[‘userfile’][‘size’] > $MAX_FILE_SIZE) { header(“Location: “ . $HOST_NAME . $SCRIPT_NAME . “?error=large”); } Run the PHP getimagesize() function to determine how the image size. If this returns FALSE, the image is invalid. Remember that the exclamation mark in the elseif means NOT: header(“Location: “ . $HOST_NAME . $SCRIPT_NAME . “?error=large”); } elseif(!getimagesize($_FILES[‘userfile’][‘tmp_name’])) { header(“Location: “ . $HOST_NAME . $SCRIPT_NAME . “?error=invalid”); } If this battery of tests does not cause the page to reload with an error, the image is legitimate and the file can be copied to a safe directory. First, specify the safe directory for images: header(“Location: “ . $HOST_NAME . $SCRIPT_NAME . “?error=invalid”); } else { $uploaddir = “/opt/lampp/htdocs/sites/auction/images/”; $uploadfile = $uploaddir . $_FILES[‘userfile’][‘name’]; NOTE Temporary Means Temporary When you upload the image with the form, the file is stored in a temporary directory. This directory really is temporary and is likely to be cleaned out regularly or on reboot. Configure this directory inside php.ini by setting the upload_tmp_dir option in php.ini. 254 Practical PHP and MySQL You create a variable called $uploaddir, which should point to a legitimate location inside the main project directory. Create a new directory called images with read and write access permissions and change $uploaddir to your directory. The second line concatenates this directory and adds the file name. The $upload- dir variable needs a trailing forward slash (/) to ensure that the image name is con- catenated correctly. Copy the file and add the name to the database: $uploaddir = “/opt/lampp/htdocs/sites/auction/images/”; $uploadfile = $uploaddir . $_FILES[‘userfile’][‘name’]; if(move_uploaded_file($_FILES[‘userfile’][‘tmp_name’], $uploadfile)) { $inssql = “INSERT INTO images(item_id, name) VALUES(“ . $validid . “, ‘“ . $_FILES[‘userfile’][‘name’] . “‘)”; mysql_query($inssql); header(“Location: “ . $HOST_NAME . $SCRIPT_NAME . “?id=” . $validid); } The move_uploaded_file() function moves the file by passing it the name of the temporary file ( $_FILES[‘userfile’][‘tmp_name’]), the destination, and the name it will be saved as ( $uploadfile). You then insert the filename and item_id into the images table and reload the page. If for some reason move_uploaded_file() fails (such as incorrect file permis- sions), display an error message: header(“Location: “ . $HOST_NAME . $SCRIPT_NAME . “?id=” . $validid); } else { echo ‘There was a problem uploading your file.<br />’; } } } With the processing complete, you can now display the existing images before the form. You can also display any error messages that resulted from the earlier tests. Select all of the records from the images table with the current item id (stored in $validid): } } } 255 CHAPTER 7 Building an Online Auction Site else { require(“header.php”); $imagessql = “SELECT * FROM images WHERE item_id = “ . $validid . “;”; $imagesresult = mysql_query($imagessql); $imagesnumrows = mysql_num_rows($imagesresult); Display the images: $imagesresult = mysql_query($imagessql); $imagesnumrows = mysql_num_rows($imagesresult); echo “<h1>Current images</h1>”; if($imagesnumrows == 0) { echo “No images.”; } else { echo “<table>”; while($imagesrow = mysql_fetch_assoc($imagesresult)) { echo “<tr>”; echo “<td><img src=’” . $config_basedir . “/images/” . $imagesrow[‘name’] . “‘ width=’100’></td>”; echo “<td>[<a href=’deleteimage.php?image_id=” . $imagesrow[‘id’] . “&item_id=” . $validid . “‘>delete</a>]</td>”; echo “</tr>”; } echo “</table>”; If no rows are returned, the text No images is displayed; otherwise, a table is created and a while loop iterates through the images. In addition to displaying the image, a link is made to a page called delete.php, and the id of both the image and item are added to the link as GET variables. After the images are displayed, the form is displayed. Just before the form code, add a switch statement to display the errors: } echo “</table>”; } switch($_GET[‘error’]) { case “empty”: echo ‘You did not select anything.’; break; case “nophoto”: echo ‘You did not select a photo to upload.’; break; 256 Practical PHP and MySQL case “photoprob”: echo ‘There appears to be a problem with the photo you are uploading’; break; case “large”: echo ‘The photo you selected is too large’; break; case “invalid”: echo ‘The photo you selected is not a valid image file’; break; } ?> Finally, add the closing curly bracket after the form and add the footer file: When you have finished adding photos, go and <a href=”<?php echo “itemdetails.php?id=” . $validid; ?>”>see your item</a>! <?php } require(“footer.php”); ?> The completed page is shown in Figure 7-6. Deleting an Image In this section, you create the Delete page that was created in the previous script. When the user clicks the Delete link, the delete.php page prompts you to verify that you want to delete the image. With this message, there will be two Submit but- tons, with either Yes and No written on them. You can then check which Submit button has been clicked and respond accordingly: ■ If the user clicks the Yes button, the image is deleted, the record is removed from the images table, and the page redirects to addimages.php. ■ If the user clicks the No button, the page redirects to addimages.php. The first step is to add the form. Create a new page called deleteimage.php and the following code: <h2>Delete image?</h2> <form action=”<?php echo pf_script_with_get($SCRIPT_NAME); ?>” method=”post”> [...]... username and password for the logins table (and keep the password handy!) STARTING TO CODE First, you need to take care of the site template, style, and some utility functions Then you can move into login screens and the actual calendar pages and scripts 267 268 Practical PHP and MySQL Site Layout and Style As you’ve done in previous chapters, the first step is to create the configuration, header, and footer... appointments, she decides to use a Web- based calendar, one she can access from any Web browser, anywhere in the world Susan goes to her calendar and enters her login details After she successfully logs in, she can see the current month, as well as each of the events she booked for that month—all located on the correct day The calendar’s sidebar 265 266 Practical PHP and MySQL also includes a list of... font-family: "trebuchet ms", verdana, sans-serif; font-size: 14px; font-weight: bold; position: absolute; height: 27px; top: 60 px; continues 269 270 Practical PHP and MySQL EXAMPLE 8-2 Continued left: 0px; width: 100%; padding: 0px; color: #000000; background-color: #eee } #header { position: absolute; top: 0px; left: 0px; height: 60 px; width: 100%; background: #333; padding-top: 8px; } #header h1 { font-size:... selects the username, email, item id, and name for all records in which dateends is in the past and in which endnotified is set to 0 Each record returned is an ended auction 259 260 Practical PHP and MySQL Iterate through the records: $itemssql = “SELECT users.username, users.email, items.id, items.name FROM items, users WHERE dateends < NOW() AND items.user_id = users.id AND endnotified = 0;”; $itemsresult... approximately every five minutes You can use the wget command-line tool to do this Create a page called processauctions .php and run a query to select all the items: < ?php require(“config .php ); require(“header .php ); $itemssql = “SELECT users.username, users.email, items.id, items.name FROM items, users WHERE dateends < NOW() AND items.user_id = users.id AND endnotified = 0;”; $itemsresult = mysql_query($itemssql);... projects, bar .php is included in the header file This file is covered in depth later in the chapter 273 274 Practical PHP and MySQL Add the small but perfectly formed footer code to footer .php, as shown in Example 8-4 EXAMPLE 8-4 and html tags The footer file closes off the main content and the body The final file to create—at least in this startup phase—is functions .php Add... file called index .php and add the code from Example 8 -6 EXAMPLE 8 -6 vious projects The login page is virtually identical to the login code from pre- < ?php session_start(); require("db .php" ); if(isset($_SESSION['LOGGEDIN']) == TRUE) { header("Location: " $config_basedir "view .php" ); } if($_POST['submit']) { $loginsql = "SELECT * FROM logins WHERE username = '" $_POST['userBox'] "' AND password = '"... provides for highly dynamic Web sites that function much like desktop applications Plug yourself in, stretch those fingers, and get ready! PROJECT OVERVIEW To get a clear idea of how the project will work, take a look at the following use case: Susan has a terrible memory Although she is extremely popular among her friends and co-workers, Susan often accepts invitations to parties and events and then promptly... answered (it does this by registering a handler to the response) 3 The PHP script that handles the request processes it and connects to the database to get the required information about the specified event 4 When the script has gathered the event information, it responds to the JavaScript handler registered in Step 2 This handler—which now contains CHAPTER 8 Creating a Web- Based Calendar the event information—replaces... is then added to bar .php (which was loaded in header .php; refer to Example 8-3) Dealing with Dates The first area of the sidebar displays the name and year of the month being viewed, and also provides arrows to allow the user to select the previous or next month These arrows link to view .php and pass it a date GET variable with the month in the format -, such as view .php? date=10-2005 (for . code: </table> </form> < ?php } require(“footer .php ); ?> 250 Practical PHP and MySQL Adding the Images Being able to upload images is a common and useful skill used when developing Web sites. The basic. is temporary and is likely to be cleaned out regularly or on reboot. Configure this directory inside php. ini by setting the upload_tmp_dir option in php. ini. 254 Practical PHP and MySQL You. use the wget command-line tool to do this. Create a page called processauctions .php and run a query to select all the items: < ?php require(“config .php ); require(“header .php ); $itemssql =

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

TỪ KHÓA LIÊN QUAN