1. Create a new document in your text editor. 2. Add the following script section to the document body. Be sure that there is nothing in the fi le before the opening PHP tag: 3. Add the following code to the script section to check if the requested fi le exists and is readable: $Dir = "files"; if (isset($_GET['filename'])) { $FileToGet = $Dir . "/" . stripslashes ($_GET['filename']); 254 CHAPTER 5 Working with Files and Directories if (is_readable($FileToGet)) { } else { $ErrorMsg = "Cannot read \"$FileToGet\""; $ShowErrorPage = TRUE; } } else { $ErrorMsg = "No filename specified"; $ShowErrorPage = TRUE; } if ($ShowErrorPage) { 4. Add the following code in the if section of the inner if...else statement for the is_readable() test to download the fi le: header("Content-Description: File Transfer"); header("Content-Type: application/force-download"); header("Content-Disposition: attachment; filename=\"" . $_GET['filename'] . "\""); header("Content-Transfer-Encoding: base64"); header("Content-Length: " . filesize($FileToGet)); readfile($FileToGet); $ShowErrorPage = FALSE; 5. Add the following code immediately after the closing PHP tag to show the error page. Note the use of advanced escaping to display the Web page output.
File Download Error There was an error downloading ""
7. Reopen ViewFiles.php. Replace the line that reads: echo "" . htmlentities($Entry). " "; 255 Uploading and Downloading Files with a line that reads: echo "" . htmlentities($Entry). " ";
8. Save ViewFiles.php and upload the fi le to the Web server. 9. Open the ViewFiles.php fi le in your Web browser by entering the following URL: http:///PHP_Projects/Chapter.05/Chapter/ViewFiles.php. Click one of the highlighted fi lenames. Your Web browser should display a save fi le dialog box like the one shown in Figure 5-8. Save the fi le and verify that it downloaded correctly. Figure 5-8 The save fi le dialog box for polarbear.gif 10. Close your Web browser window.
1. Create a new document in your text editor. 2. Type the declaration, element, header information, and
element. Use the strict DTD and Visitor Comments as the content of the
element. 3. Add the following script section to the document body: 4. Add the following code to the script section to store the form data entered: $Dir = "comments"; if (is_dir($Dir)) { if (isset($_POST['save'])) { if (empty($_POST['name'])) $SaveString = "Unknown Visitor "; else $SaveString = stripslashes ($_POST['name']) . " "; $SaveString .= stripslashes ($_POST['email']) . " "; $SaveString .= date('r') . " "; $SaveString .= stripslashes ($_POST['comment']); $CurrentTime = microtime(); $TimeArray = explode(" ", $CurrentTime); $TimeStamp = (float)$TimeArray[1] + (float)$TimeArray[0]; In a publicly accessible application on the Internet, using the microtime() function would not be suffi cient to guarantee a unique fi lename, although it is suffi cient to use in this exercise. 258 CHAPTER 5 Working with Files and Directories /* File name is " Comment.seconds. microseconds.txt" */ $SaveFileName = "$Dir/Comment.$TimeStamp. txt"; if (file_put_contents($SaveFileName, $SaveString)>0) echo "File \"" . htmlentities ($SaveFileName) . "\" successfully saved.
"; else echo "There was an error writing \"" . htmlentities($SaveFileName) . "\".
"; } } 5. Add the following XHTML form immediately after the closing PHP tag:
Visitor Comments
6. Save the document as VisitorComments.php in the Chapter directory for Chapter 5 and upload the fi le to the server. 7. Create a new subdirectory named comments. Verify that the comments directory on the Web server has read, write, and execute permissions enabled for user, group, and other. 8. Reopen ViewFiles.php, change the title to View Comments, and immediately save the fi le as ViewComments.php. 9. Change the value of $Dir to "comments", as follows: $Dir = "comments"; 10. Convert the code that uses FileDownloader.php back to a standard hyperlink, as follows: echo "" . htmlentities($Entry). ""; 11. Save ViewComments.php in the Chapter directory for Chapter 5 and upload the fi le to the server. 12. Open the VisitorComments.php fi le in your Web browser by entering the following URL: http:///PHP_Projects/Chapter.05/Chapter/VisitorComments.php. Attempt For most uses, granting write permission to others is not a safe choice. When making this choice, be sure you have considered the security risks. Do not grant write permissions unless it is absolutely required. 259 Reading and Writing Entire Filesto submit a comment. You should receive a message stating whether the comment was saved successfully. Figure 5-9 shows an example in which the comment was successfully saved. Figure 5-9 A successfully written comment using VisitorComments.php 13. After you have successfully submitted one or more comments to the server using the VisitorComments.php form, open the ViewComments.php fi le in your Web browser by entering the following URL: http:///PHP_Projects/ Chapter.05/Chapter/ViewComments.php. You should see the new fi les in the directory listing. Figure 5-10 shows the output of ViewComments.php with two comments submitted. Figure 5-10 Listing of the comments subdirectory with two saved comments 14. Close your Web browser window. 1. Create a new document in your text editor. 2. Type the declaration, element, header information, and
element. Use the strict DTD and Visitor Feedback as the content of the element. 3. Add the following script section to the document body: 4. Add the following code to the script section to store the form data entered: $Dir = "comments"; if (is_dir($Dir)) { $CommentFiles = scandir($Dir); foreach ($CommentFiles as $FileName) { if (($FileName != ".") && ($FileName != "..")) { echo "From $FileName
"; echo " "; $Comment = file_get_contents ($Dir . "/" . $FileName); echo $Comment; echo "
"; echo "
"; } } } 5. Add the following XHTML form immediately before the closing PHP tag: Visitor Feedback
6. Save the document as VisitorFeedback.php in the Chapter directory for Chapter 5 and upload the fi le to the server. 7. Open the VisitorFeedback.php fi le in your Web browser by entering the following URL: http:/// PHP_Projects/Chapter.05/Chapter/VisitorFeedback.php. You should see a list of all the user comments from the comments subdirectory. Figure 5-12 shows an example with two comments. 263 Reading and Writing Entire Files8. Close your Web browser window. Figure 5-12 The Visitor Feedback page with two visitor comments If you only want to display the contents of a text fi le, you do not need to use the file_get_contents() function to assign the contents to a variable and then display the value of the variable as a separate step. Instead, you can use the readfile() function discussed earlier to display the contents of a text fi le to a Web browser. For example, the following example uses the readfile() function to accomplish the same task as the file_get_contents() example you saw earlier: readfile("sfweather.txt"); At times, text fi les are used to store individual lines of data, where each line represents a single unit of information. e easiest way to read the contents of a text fi le that stores data on individual lines is to use the file() function, which reads the entire contents of a fi le into an indexed array. e file() function automatically recognizes whether the lines in a text fi le end in , , or . Each individual line in the text fi le is assigned as the value of an element. You pass to the file() function the name of the text fi le enclosed in quotation marks. For example, the weather service that stores daily weather reports may also store average daily high, low, and mean temperatures, separated by commas, on individual lines in a single text fi le. e following code uses the file_put_contents() function to write the temperatures for the fi rst week in January to a text fi le named s anaverages.txt: $January = "61, 42, 48 "; $January .= "62, 41, 49 "; 264 CHAPTER 5 Working with Files and Directories - Feedback - Mozilla Firefox 1 xl File Edit View History Bookmarks lools Help - C \j 1 0|http://student200.ucb.sephone.us/PHP_frojects/Chapter.05/Chapter/VisitorFeedback!php""Visitor Feedback From Comment.l240187766.2.txt Joseph Michaels jm0example.com Sun, 19 Apr 2009 20:36:06 -0400 Ireally like your sice. From Comment.l240187812.43.txt Nancy Daniels nancy.danielsSexample.edu Sun, 19 Apr 2009 20:36:52 -0400 Ireally don'c like your srce. j Done$January .= "62, 41, 49 "; $January .= "64, 40, 51 "; $January .= "69, 44, 55 "; $January .= "69, 45, 52 "; $January .= "67, 46, 54 "; file_put_contents("sfjanaverages.txt", $January); e fi rst statement in the following code uses the file() function to read the contents of the s anaverages.txt fi le into an indexed array named $JanuaryTemps[]. e for statement then loops through each element in $JanuaryTemps[] and calls the explode() function from Chapter 3 to split each element at the comma into another array named $CurDay. e high, low, and mean averages in the $CurDay array are then displayed with echo statements. Figure 5-13 shows the output. $JanuaryTemps = file("sfjanaverages.txt"); for ($i=0; $iJanuary " . ($i + 1) . "
"; echo "High: {$CurDay[0]}
"; echo "Low: {$CurDay[1]}
"; echo "Mean: {$CurDay[2]} "; } Figure 5-13 Output of individual lines in a text fi le 265 Reading and Writing Entire Files )january Temperatures - Mozilla Firefox - I x I File Edit View History Bookmarks lools Help c x ... |Q | http://student200.ucb.sephone.L * January1 High; 61 Low: 42 Mean: 48 January 2 High: 62 Low: 41 Mean: 49 January 3 High: 62 Low: 41 Mean: 49 | Done ATo modify the VisitorFeedback.php fi le so it opens the comment fi les with the file() function instead of the file_get_contents() function: 1. Return to the VisitorFeedback.php fi le in your text editor. 2. Replace the section of code from the opening statement to the closing
statement with the following code. Notice that because the fi rst three lines of the comment are the commenters name and e-mail address and the date of the comment, the loop to display the comment text has a starting index of 3. $Comment = file($Dir . "/" . $FileName); echo "From: " . htmlentities($Comment[0]) . "
"; echo "Email Address: " . htmlentities($Comment[1]) . "
"; echo "Date: " . htmlentities($Comment[2]) . "
"; $CommentLines = count($Comment); echo "Comment:
"; for ($i = 3; $i < $CommentLines; ++$i) { echo htmlentities($Comment[$i]) . "
"; } 3. Save the VisitorFeedback.php fi le and upload it to the Web server. 4. Open the VisitorFeedback.php fi le in your Web browser by entering the following URL: http:///PHP_Projects/ Chapter.05/Chapter/VisitorFeedback.php. Figure 5-14 shows the new version of the Web page for the same two comments. Figure 5-14 The Visitor Feedback form using the file() function 5. Close your Web browser window.