PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 18.6 Reading a File into a String

18.6.1 Problem

You want to load the entire contents of a file into a variable. For example, you want to determine if the text in a file matches a regular expression.

18.6.2 Solution

Use filesize( ) to get the size of the file, and then tell fread( ) to read that many bytes:

$fh = fopen('people.txt','r') or die($php_errormsg);
$people = fread($fh,filesize('people.txt'));
if (preg_match('/Names:.*(David|Susannah)/i',$people)) {
    print "people.txt matches.";
}
fclose($fh) or die($php_errormsg);

18.6.3 Discussion

To read a binary file (e.g., an image) on Windows, a b must be appended to the file mode:

$fh = fopen('people.jpg','rb') or die($php_errormsg);
$people = fread($fh,filesize('people.jpg'));
fclose($fh);

There are easier ways to print the entire contents of a file than by reading it into a string and then printing the string. PHP provides two functions for this. The first is fpassthru($fh), which prints everything left on the file handle $fh and then closes it. The second, readfile($filename), prints the entire contents of $filename.

You can use readfile( ) to implement a wrapper around images that shouldn't always be displayed. This program makes sure a requested image is less than a week old:

$image_directory = '/usr/local/images';

if (preg_match('/^[a-zA-Z0-9]+\.(gif|jpeg)$/',$image,$matches) &&
    is_readable($image_directory."/$image") &&
    (filemtime($image_directory."/$image") >= (time() - 86400 * 7))) {

  header('Content-Type: image/'.$matches[1]);
  header('Content-Length: '.filesize($image_directory."/$image"));

  readfile($image_directory."/$image");

} else {
  error_log("Can't serve image: $image");
}

The directory in which the images are stored, $image_directory, needs to be outside the web server's document root for the wrapper to be effective. Otherwise, users can just access the image files directly. You test the image for three things. First, that the filename passed in $image is just alphanumeric with an ending of either .gif or .jpeg. You need to ensure that characters such as .. or / are not in the filename; this prevents malicious users from retrieving files outside the specified directory. Second, use is_readable( ) to make sure you can read the file. Finally, get the file's modification time with filemtime( ) and make sure that time is after 86400 x 7 seconds ago. There are 86,400 seconds in a day, so 86400 x 7 is a week.[1] If all of these conditions are met, you're ready to send the image. First, send two headers to tell the browser the image's MIME type and file size. Then use readfile( ) to send the entire contents of the file to the user.

[1] When switching between standard time and daylight saving time, there are not 86,400 seconds in a day. See Section 3.11 for details.

18.6.4 See Also

Documentation on filesize( ) at http://www.php.net/filesize, fread( ) at http://www.php.net/fread, fpassthru( ) at http://www.php.net/fpassthru, and readfile( ) at http://www.php.net/readfile.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    Chapter 5. Variables
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    18.1 Introduction
    Recipe 18.2 Creating or Opening a Local File
    Recipe 18.3 Creating a Temporary File
    Recipe 18.4 Opening a Remote File
    Recipe 18.5 Reading from Standard Input
    Recipe 18.6 Reading a File into a String
    Recipe 18.7 Counting Lines, Paragraphs, or Records in a File
    Recipe 18.8 Processing Every Word in a File
    Recipe 18.9 Reading a Particular Line in a File
    Recipe 18.10 Processing a File Backward by Line or Paragraph
    Recipe 18.11 Picking a Random Line from a File
    Recipe 18.12 Randomizing All Lines in a File
    Recipe 18.13 Processing Variable Length Text Fields
    Recipe 18.14 Reading Configuration Files
    Recipe 18.15 Reading from or Writing to a Specific Location in a File
    Recipe 18.16 Removing the Last Line of a File
    Recipe 18.17 Modifying a File in Place Without a Temporary File
    Recipe 18.18 Flushing Output to a File
    Recipe 18.19 Writing to Standard Output
    Recipe 18.20 Writing to Many Filehandles Simultaneously
    Recipe 18.21 Escaping Shell Metacharacters
    Recipe 18.22 Passing Input to a Program
    Recipe 18.23 Reading Standard Output from a Program
    Recipe 18.24 Reading Standard Error from a Program
    Recipe 18.25 Locking a File
    Recipe 18.26 Reading and Writing Compressed Files
    Recipe 18.27 Program: Unzip
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele