Specifications
You should also add locks to vieworders.php:
$fp = fopen(“$DOCUMENT_ROOT /../orders/orders.txt”, “r”);
flock($fp, 1); // lock file for reading
// read from the file
flock($fp, 3); // release read lock
fclose($fp);
Our code is now more robust, but still not perfect. What if two scripts tried to acquire a lock at
the same time? This would result in a race condition, where the processes compete for locks
but it is uncertain which will succeed, that could cause more problems. We can do better by
using a DBMS.
Doing It a Better Way: Database Management
Systems
So far all the examples we have looked at use flat files. In the next section of this book we’ll
look at how you can use MySQL, a relational database management system, instead. You
might ask, “Why would I bother?”
Problems with Using Flat Files
There are a number of problems in working with flat files:
• When a file gets large, it can be very slow to work with.
• Searching for a particular record or group of records in a flat file is difficult. If the
records are in order, you can use some kind of binary search in conjunction with a fixed-
width record to search on a key field. If you want to find patterns of information (for
example, you want to find all the customers who live in Smalltown), you would have to
read in each record and check it individually.
• Dealing with concurrent access can become problematic. We have seen how you can lock
files, but this can cause a race condition we discussed earlier. It can also cause a bottle-
neck. With enough traffic on the site, a large group of users may be waiting for the file to
be unlocked before they can place their order. If the wait is too long, people will go else-
where to buy.
• All the file processing we have seen so far deals with a file using sequential processing—
that is, we start from the start of the file and read through to the end. If we want to insert
records into or delete records from the middle of the file (random access), this can be
difficult—you end up reading the whole file into memory, making the changes, and writ-
ing the whole file out again. With a large data file, this becomes a significant overhead.
• Beyond the limits offered by file permissions, there is no easy way of enforcing different
levels of access to data.
Using PHP
P
ART I
66
04 7842 CH02 3/6/01 3:37 PM Page 66