Beginning PHP and MySQL From Novice to Professional phần 4 pps

108 343 0
Beginning PHP and MySQL From Novice to Professional 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

290 CHAPTER 10 ■ WORKING WITH THE FILE AND OPERATING SYSTEM Reading a File into an Array The file() function is capable of reading a file into an array, separating each element by the newline character, with the newline still attached to the end of each element. Its prototype follows: array file(string filename [int use_include_path [, resource context]]) Although simplistic, the importance of this function can’t be overstated, and therefore it warrants a simple demonstration. Consider the following sample text file named users.txt: Ale ale@example.com Nicole nicole@example.com Laura laura@example.com The following script reads in users.txt and parses and converts the data into a convenient Web-based format. Notice file() provides special behavior because unlike other read/write functions, you don’t have to establish a file handle in order to read it: <?php // Read the file into an array $users = file("users.txt"); // Cycle through the array foreach ($users as $user) { // Parse the line, retrieving the name and e-mail address list($name, $email) = explode(" ", $user); // Remove newline from $email $email = trim($email); // Output the formatted name and e-mail address echo "<a href=\"mailto:$email\">$name</a> <br /> "; } ?> Gilmore_862-8C10.fm Page 290 Tuesday, February 12, 2008 9:14 AM CHAPTER 10 ■ WORKING WITH THE FILE AND OPERATING SYSTEM 291 This script produces the following HTML output: <a href="ale@example.com">Ale</a><br /> <a href="nicole@example.com">Nicole</a><br /> <a href="laura@example.com">Laura</a><br /> Like fopen(), you can tell file() to search through the paths specified in the include_path configuration parameter by setting use_include_path to 1. The context parameter refers to a stream context. You’ll learn more about this topic in Chapter 16. Reading File Contents into a String Variable The file_get_contents() function reads the contents of a file into a string. Its proto- type follows: string file_get_contents(string filename [, int use_include_path [resource context]]) By revising the script from the preceding section to use this function instead of file(), you get the following code: <?php // Read the file into a string variable $userfile= file_get_contents("users.txt"); // Place each line of $userfile into array $users = explode("\n",$userfile); // Cycle through the array foreach ($users as $user) { // Parse the line, retrieving the name and e-mail address list($name, $email) = explode(" ", $user); // Output the formatted name and e-mail address echo "<a href=\"mailto:$email\">$name/a> <br />"; Gilmore_862-8C10.fm Page 291 Tuesday, February 12, 2008 9:14 AM 292 CHAPTER 10 ■ WORKING WITH THE FILE AND OPERATING SYSTEM } ?> The use_include_path and context parameters operate in a manner identical to those defined in the preceding section. Reading a CSV File into an Array The convenient fgetcsv() function parses each line of a file marked up in CSV format. Its prototype follows: array fgetcsv(resource handle [, int length [, string delimiter [, string enclosure]]]) Reading does not stop on a newline; rather, it stops when length characters have been read. As of PHP 5, omitting length or setting it to 0 will result in an unlimited line length; however, since this degrades performance it is always a good idea to choose a number that will certainly surpass the longest line in the file. The optional delimiter parameter (by default set to a comma) identifies the character used to delimit each field. The optional enclosure parameter (by default set to a double quote) identifies a character used to enclose field values, which is useful when the assigned delimiter value might also appear within the field value, albeit under a different context. ■Note Comma-separated value (CSV) files are commonly used when importing files between applications. Microsoft Excel and Access, MySQL, Oracle, and PostgreSQL are just a few of the applications and data- bases capable of both importing and exporting CSV data. Additionally, languages such as Perl, Python, and PHP are particularly efficient at parsing delimited data. Consider a scenario in which weekly newsletter subscriber data is cached to a file for perusal by the marketing staff. This file might look like this: Jason Gilmore,jason@example.com,614-555-1234 Bob Newhart,bob@example.com,510-555-9999 Carlene Ribhurt,carlene@example.com,216-555-0987 Always eager to barrage the IT department with dubious requests, the marketing staff asks that the information also be made available for viewing on the Web. Thank- fully, this is easily accomplished with fgetcsv(). The following example parses the file: Gilmore_862-8C10.fm Page 292 Tuesday, February 12, 2008 9:14 AM CHAPTER 10 ■ WORKING WITH THE FILE AND OPERATING SYSTEM 293 <?php // Open the subscribers data file $fh = fopen("/home/www/data/subscribers.csv", "r"); // Break each line of the file into three parts while (list($name, $email, $phone) = fgetcsv($fh, 1024, ",")) { // Output the data in HTML format printf("<p>%s (%s) Tel. %s</p>", $name, $email, $phone); } ?> Note that you don’t have to use fgetcsv() to parse such files; the file() and list() functions accomplish the job quite nicely. Reconsider the preceding example: <?php // Read the file into an array $users = file("/home/www/data/subscribers.csv"); foreach ($users as $user) { // Break each line of the file into three parts list($name, $email, $phone) = explode(",", $user); // Output the data in HTML format printf("<p>%s (%s) Tel. %s</p>", $name, $email, $phone); } ?> Reading a Specific Number of Characters The fgets() function returns a certain number of characters read in through the opened resource handle, or everything it has read up to the point when a newline or an EOF character is encountered. Its prototype follows: string fgets(resource handle [, int length]) Gilmore_862-8C10.fm Page 293 Tuesday, February 12, 2008 9:14 AM 294 CHAPTER 10 ■ WORKING WITH THE FILE AND OPERATING SYSTEM If the optional length parameter is omitted, 1,024 characters is assumed. In most situations, this means that fgets() will encounter a newline character before reading 1,024 characters, thereby returning the next line with each successive call. An example follows: <?php // Open a handle to users.txt $fh = fopen("/home/www/data/users.txt", "rt"); // While the EOF isn't reached, read in another line and output it while (!feof($fh)) echo fgets($fh); // Close the handle fclose($fh); ?> Stripping Tags from Input The fgetss() function operates similarly to fgets(), except that it also strips any HTML and PHP tags from the input. Its prototype follows: string fgetss(resource handle, int length [, string allowable_tags]) If you’d like certain tags to be ignored, include them in the allowable_tags param- eter. As an example, consider a scenario in which contributors are expected to submit their work in HTML format using a specified subset of HTML tags. Of course, the authors don’t always follow instructions, so the file must be filtered for tag misuse before it can be published. With fgetss(), this is trivial: <?php // Build list of acceptable tags $tags = "<h2><h3><p><b><a><img>"; // Open the article, and read its contents. $fh = fopen("article.html", "rt"); while (!feof($fh)) { $article .= fgetss($fh, 1024, $tags); } Gilmore_862-8C10.fm Page 294 Tuesday, February 12, 2008 9:14 AM CHAPTER 10 ■ WORKING WITH THE FILE AND OPERATING SYSTEM 295 // Close the handle fclose($fh); // Open the file up in write mode and output its contents. $fh = fopen("article.html", "wt"); fwrite($fh, $article); // Close the handle fclose($fh); ?> ■Tip If you want to remove HTML tags from user input submitted via a form, check out the strip_tags() function, introduced in Chapter 9. Reading a File One Character at a Time The fgetc() function reads a single character from the open resource stream speci- fied by handle. If the EOF is encountered, a value of FALSE is returned. Its prototype follows: string fgetc(resource handle) Ignoring Newline Characters The fread() function reads length characters from the resource specified by handle. Reading stops when the EOF is reached or when length characters have been read. Its prototype follows: string fread(resource handle, int length) Note that unlike other read functions, newline characters are irrelevant when using fread(); therefore, it’s often convenient to read the entire file in at once using filesize() to determine the number of characters that should be read in: Gilmore_862-8C10.fm Page 295 Tuesday, February 12, 2008 9:14 AM 296 CHAPTER 10 ■ WORKING WITH THE FILE AND OPERATING SYSTEM <?php $file = "/home/www/data/users.txt"; // Open the file for reading $fh = fopen($file, "rt"); // Read in the entire file $userdata = fread($fh, filesize($file)); // Close the file handle fclose($fh); ?> The variable $userdata now contains the contents of the users.txt file. Reading in an Entire File The readfile() function reads an entire file specified by filename and immediately outputs it to the output buffer, returning the number of bytes read. Its prototype follows: int readfile(string filename [, int use_include_path]) Enabling the optional use_include_path parameter tells PHP to search the paths specified by the include_path configuration parameter. This function is useful if you’re interested in simply dumping an entire file to the browser: <?php $file = "/home/www/articles/gilmore.html"; // Output the article to the browser. $bytes = readfile($file); ?> Like many of PHP’s other file I/O functions, remote files can be opened via their URL if the configuration parameter fopen_wrappers is enabled. Gilmore_862-8C10.fm Page 296 Tuesday, February 12, 2008 9:14 AM CHAPTER 10 ■ WORKING WITH THE FILE AND OPERATING SYSTEM 297 Reading a File According to a Predefined Format The fscanf() function offers a convenient means for parsing a resource in accordance with a predefined format. Its prototype follows: mixed fscanf(resource handle, string format [, string var1]) For example, suppose you want to parse the following file consisting of Social Security numbers (SSN) (socsecurity.txt): 123-45-6789 234-56-7890 345-67-8901 The following example parses the socsecurity.txt file: <?php $fh = fopen("socsecurity.txt", "r"); // Parse each SSN in accordance with integer-integer-integer format while ($user = fscanf($fh, "%d-%d-%d")) { // Assign each SSN part to an appropriate variable list ($part1,$part2,$part3) = $user; printf(Part 1: %d Part 2: %d Part 3: %d <br />", $part1, $part2, $part3); } fclose($fh); ?> With each iteration, the variables $part1, $part2, and $part3 are assigned the three components of each SSN, respectively, and output to the browser. Writing a String to a File The fwrite() function outputs the contents of a string variable to the specified resource. Its prototype follows: int fwrite(resource handle, string string [, int length]) Gilmore_862-8C10.fm Page 297 Tuesday, February 12, 2008 9:14 AM 298 CHAPTER 10 ■ WORKING WITH THE FILE AND OPERATING SYSTEM If the optional length parameter is provided, fwrite() will stop writing when length characters have been written. Otherwise, writing will stop when the end of the string is found. Consider this example: <?php // Data we'd like to write to the subscribers.txt file $subscriberInfo = "Jason Gilmore|jason@example.com"; // Open subscribers.txt for writing $fh = fopen("/home/www/data/subscribers.txt", "at"); // Write the data fwrite($fh, $subscriberInfo); // Close the handle fclose($fh); ?> ■Tip If the optional length parameter is not supplied to fwrite(), the magic_quotes_runtime configuration parameter will be disregarded. See Chapters 2 and 9 for more information about this parameter. This only applies to PHP 5 and earlier. Moving the File Pointer It’s often useful to jump around within a file, reading from and writing to various locations. Several PHP functions are available for doing just this. Moving the File Pointer to a Specific Offset The fseek() function moves the pointer to the location specified by a provided offset value. Its prototype follows: int fseek(resource handle, int offset [, int whence]) If the optional parameter whence is omitted, the position is set offset bytes from the beginning of the file. Otherwise, whence can be set to one of three possible values, which affect the pointer’s position: Gilmore_862-8C10.fm Page 298 Tuesday, February 12, 2008 9:14 AM [...]... available for this task and also introduces a function new to PHP 5 that reads a directory’s contents into an array Opening a Directory Handle Just as fopen() opens a file pointer to a given file, opendir() opens a directory stream specified by a path Its prototype follows: resource opendir(string path) Closing a Directory Handle The closedir() function closes the directory stream Its prototype follows: void... distribution’s root directory This file installs the PEAR command, the necessary support files, and the aforementioned six PEAR packages Initiate the installation process by changing to the PHP root directory and executing go-pear.bat, like so: %>go-pear.bat You’ll be prompted to confirm a few configuration settings such as the location of the PHP root directory and executable; you’ll likely be able to accept the... the package name and version To learn more about a package, execute the info command, passing it the package name For example, you would execute the following command to learn more about the Console_Getopt package: %>pear info Console_Getopt Here’s an example of output from this command: ABOUT CONSOLE_GETOPT-1.2 ======================== Provides Classes: Console_Getopt Package Console_Getopt Summary Description... said, before delving into this powerful feature, take a moment to consider the topic of sanitizing user input before passing it to the shell level Sanitizing the Input Neglecting to sanitize user input that may subsequently be passed to system-level functions could allow attackers to do massive internal damage to your information store and operating system, deface or delete Web files, and otherwise gain... introduced to the PHP Extension and Application Repository (PEAR) and the online community repository for distributing and sharing code Gilmore_862-8C11.fm Page 309 Wednesday, February 13, 2008 7:02 AM CHAPTER 11 ■■■ PEAR Good programmers write solid code, while great programmers reuse the code of good programmers For PHP programmers, PEAR, the acronym for PHP Extension and Application Repository, is... offset within the resource Its prototype follows: int ftell(resource handle) Moving the File Pointer Back to the Beginning of the File The rewind() function moves the file pointer back to the beginning of the resource Its prototype follows: int rewind(resource handle) Reading Directory Contents The process required for reading a directory’s contents is quite similar to that involved in reading a file... closedir(resource directory_handle) Parsing Directory Contents The readdir() function returns each element in the directory Its prototype follows: 299 Gilmore_862-8C10.fm Page 300 Tuesday, February 12, 2008 9: 14 AM 300 CH APT ER 10 ■ WO RKI NG WI TH T HE FI LE A ND O PE RAT IN G SYS TE M string readdir(int directory_handle) Among other things, you can use this function to list all files and child directories in... The scandir() function, introduced in PHP 5, returns an array consisting of files and directories found in directory, or returns FALSE on error Its prototype follows: array scandir(string directory [,int sorting_order [, resource context]]) Setting the optional sorting_order parameter to 1 sorts the contents in descending order, overriding the default of ascending order Executing this example (from. .. required for PEAR to run properly • Console_Getopt: It’s possible to create PHP programs that execute from the command line, much like you might be doing with Perl or shell scripts Often the behavior of these programs is tweaked The Console_Getopt package provides a standard means for reading these options and providing the user with error messages if the supplied syntax does not correspond to some predefined... /usr/local/apache/htdocs/ And the final command is this: rm -rf * The last two commands are certainly unexpected and could result in the deletion of your entire Web document tree One way to safeguard against such attempts is to sanitize user input before it is passed to any of PHP s program execution functions Two standard functions are conveniently available for doing so: escapeshellarg() and escapeshellcmd() . parameter. This only applies to PHP 5 and earlier. Moving the File Pointer It’s often useful to jump around within a file, reading from and writing to various locations. Several PHP functions are available. available for this task and also introduces a function new to PHP 5 that reads a directory’s contents into an array. Opening a Directory Handle Just as fopen() opens a file pointer to a given file,. THE FILE AND OPERATING SYSTEM string readdir(int directory_handle) Among other things, you can use this function to list all files and child directories in a given directory: < ?php $dh =

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

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

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

Tài liệu liên quan