O'Reilly logo

Programming PHP, 3rd Edition by Rasmus Lerdorf, Peter MacIntyre, Kevin Tatroe

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Direct File-Level Manipulation

PHP has many little hidden features within its vast toolset. One of these features (which is often overlooked) is its uncanny capability to handle complex files—sure, everyone knows that PHP can open a file, but what can it really do with that file? What actually brought the true range of possibilities to my attention was a request from a prospective client who had “no money,” but wanted a dynamic web survey developed. Of course, I initially offered the client the wonders of PHP and database interaction with MySQLi. Upon hearing the monthly fees from a local ISP, however, the client asked if there was any other way to have the work accomplished. It turns out that if you don’t want to use SQLite, another alternative is to use files to manage and manipulate small amounts of text for later retrieval. The functions we’ll discuss here are nothing out of the ordinary when taken individually—in fact, they’re really part of the basic PHP toolset everyone is probably familiar with, as you can see in Table 8-2.

Table 8-2. Commonly used PHP file management functions

Function name

Description of use

mkdir()

Used to make a directory on the server.

file_exists()

Used to determine if a file or directory exists at the supplied location.

fopen()

Used to open an existing file for reading or writing (see detailed options for correct usage).

fread()

Used to read in the contents of a file to a variable for PHP use.

flock()

Used to gain an exclusive lock on a file for writing.

fwrite() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required