25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Streams and Network Programming ” 243<br />

Simple File Functions<br />

In addition to the “traditional” C-like file-access functions, <strong>PHP</strong> provides a set of<br />

simplified functions that, effectively, allow you to perform multiple file-related operations<br />

with a single function call.<br />

As an example, readfile() will read a file and write it immediately to the script’s<br />

standard output; this is useful when you need to include static files, as it offers much<br />

better performance and resource utilization than C-style functions:<br />

i<br />

header("content-type: video/mpeg");<br />

readfile("my_home_movie.mpeg");<br />

Similarly, file() will let you read a file into an array of lines (that is one array element<br />

for each line of text in the file). Prior to <strong>PHP</strong> 4.3.0, it was common to use this function<br />

together with implode() as a quick-and-dirty way to load an entire file into memory.<br />

More recent versions of <strong>PHP</strong> provide the file_get_contents() function specifically<br />

for this purpose:<br />

// Old Way<br />

$file = implode("\r\n", file("myfile.txt"));<br />

// New Way<br />

$file = file_get_contents("myfile.txt");<br />

Loading an entire file in memory is not always a good idea—large files require a significant<br />

amount of system resources and will very rapidly starve your server under load.<br />

You can, however, limit the amount of data read by file_get_contents() by specifying<br />

an appropriate set of parameters to the function.<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

As of <strong>PHP</strong> 5.0.0, file_put_contents() was added to the language core to simplify<br />

the writing of data to files. Like file_get_contents(), file_put_contents() allows<br />

you to write the contents of a <strong>PHP</strong> string to a file in one pass:<br />

$data = "My Data";<br />

file_put_contents("myfile.txt", $data, FILE_APPEND);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!