Specifications

File Locking
Imagine a situation where two customers are trying to order a product at the same time. (Not
uncommon, especially when you start to get any kind of volume of traffic on a Web site.) What
if one customer calls fopen() and begins writing, and then the other customer calls fopen()
and also begins writing? What will be the final contents of the file? Will it be the first order
followed by the second order, or vice versa? Will it be one order or the other? Or will it be
something less useful, like the two orders interleaved somehow? The answer depends on your
operating system, but is often impossible to know.
To avoid problems like this, you can use file locking. This is implemented in PHP using the
flock() function. This function should be called after a file has been opened, but before any
data is read from or written to the file.
The prototype for flock() is
bool flock(int fp, int operation);
You need to pass it a pointer to an open file and a number representing the kind of lock you
require. It returns true if the lock was successfully acquired, and false if it was not.
The possible values of operation are shown in Table 2.2.
TABLE 2.2 flock() Operation Values
Value of Operation Meaning
1 Reading lock. This means the file can be shared with other
readers.
2 Writing lock. This is exclusive. The file cannot be shared.
3 Release existing lock.
+4 Adding 4 to the operation prevents blocking while trying to acquire
a lock.
If you are going to use flock(), you will need to add it to all the scripts that use the file; oth-
erwise, it is worthless.
To use it with this example, you can alter processorder.php as follows:
$fp = fopen(“$DOCUMENT_ROOT/../orders/orders.txt”, “a”, 1);
flock($fp, 2); // lock the file for writing
fwrite($fp, $outputstring);
flock($fp, 3); // release write lock
fclose($fp);
Storing and Retrieving Data
C
HAPTER 2
2
STORING AND
RETRIEVING DATA
65
04 7842 CH02 3/6/01 3:37 PM Page 65