6.4 Storing a File into Your Program


You want to copy an entire file into memory all in one move.

Technique

If you want to load the file into a variable, use the fread() function in conjunction with the filesize() function:

 <?php $fp = @fopen ("http://www.designmultimedia.com/", "r") or   die ("Cannot open URL: designmultimedia.com"); $f_contents = fread ($fp, filesize ($fp)); @fclose ($fp); ?> 

Or, if you want to read the file into an array of lines, use the file() function:

 $f_contents = file('http://www.designmultimedia.com/'); 

Finally, here's an alternative way (using file() ) to load the contents into one big variable:

 $f_contents = implode ("", file ('http://www.designmultimedia.com/')); 

Comments

In PHP, as shown here, there are multiple ways to do the same thing. If we wanted to copy a file into memory line-by-line , we could also do the following:

 <?php $fp = @fopen( "ftp://ftp.designmultimedia.com", "r" ) or             die("Cannot Open FTP Connection: ftp.designmultimedia.com"); while ($line = @fgets ($fp, 1024)) {     $f_contents .= $line; } @fclose ($fp); ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net