18.5. Reading a File into a String
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.
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);
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: ...
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.