25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Streams and Network Programming ” 239<br />

Accessing Files<br />

<strong>PHP</strong> provides several different ways to create, read from and write to files, depending<br />

on the type of operation that you need to perform. First up, we have the more<br />

traditional, C-style functions. Just like their C counterparts, these open/create, read,<br />

write and close a file handle. A file handle is a reference to an external resource—this<br />

means you are not loading the entire file into memory when manipulating it, but<br />

simply dealing with a reference to it. Thus, this family of functions is very resource<br />

friendly and—while considered somewhat antiquated and arcane in comparison to<br />

some of the more recent additions to <strong>PHP</strong>—is still best-practice material when it<br />

comes to dealing with large files:<br />

$file = fopen("counter.txt", ’a+’);<br />

if ($file == false) {<br />

die ("Unable to open/create file");<br />

}<br />

if (filesize("counter.txt") == 0) {<br />

$counter = 0;<br />

} else {<br />

$counter = (int) fgets($file);<br />

}<br />

ftruncate($file, 0);<br />

$counter++;<br />

fwrite($file, $counter);<br />

echo "There has been $counter hits to this site.";<br />

In this example, we start by opening the file using fopen(); we will use the resulting<br />

resource when calling every other function that will work with our file. Note that<br />

fopen() returns false upon failure—and we must check for it explicitly to ensure<br />

that <strong>PHP</strong> doesn’t play any automatic-conversion tricks on us.<br />

Next up, we use filesize() to make sure that the file is not empty and our counter<br />

has been started. If it is empty, we set the counter to 0; otherwise, we grab the first<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)

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

Saved successfully!

Ooh no, something went wrong!