PHP Diary | PHP Housekeeping | PHP Scripts | TD Scripts.com
TD Keno - Offer your site visitors an engaging Keno game without the monetary risk


[back]
WB01624_.gif (281 bytes) 02/15/00 "Using flock to protect files from corruption" WB01626_.gif (272 bytes)[next]

Read/Write conflicts

Something I haven't gone over yet in my diary entries is a very useful function called, flock. Let's go back to our counter example because it will best illustrate how file corruption could occur. Let's say two visitors come to my main page at almost the same time, one of them is in the file open phase while the other is in the file writing phase of the code. A count likely could be lost because you can't read and write the same file simultaneously. What you can do, however, is use flock to LOCK the file while you are reading and writing to it so no other processes can try to read or write to it until the process is finished. So essentially visitor number 2 process will wait for for visitor number 1 process to finish. I use flock frequently, and you should as well, when you have a file that is being (or likely to be) accessed repeatedly. Let's see how the PHP manual describes the function:

bool flock(int fp, int operation);

Let's add flock to the counter script from last month:

<?
if(file_exists("count.dat"))
{
  $exist_file = fopen("count.dat", "r");
  flock($new_file, 2);
  $new_count = fgets($exist_file, 255);

  $new_count++;
  flock($new_file, 3);
  fclose($exist_file);
  // to be invisible counter comment out next line;
  print("$new_count people have visited this page");

  $exist_count = fopen("count.dat", "w");
  flock($new_file, 2);
  fputs($exist_count, $new_count);
  flock($new_file, 3);
  fclose($exist_count);
}
else
{
$new_file = fopen("count.dat", "w");
flock($new_file, 2);
fputs($new_file, "1");
flock($new_file, 3);
fclose($new_file);
}
?>
 

Modifying the counter script using "w+"

It is possible to use "w+" as an open read/write mode for a file handle as opposed to doing as I did above. The fopen syntax would look as follows:

$exist_file = fopen("count.dat", "r+");

File Read/Write modes

r = read only
w = write, overwrites prior contents if any
a = append, adds to end of prior contents, if any

r+ = read and write
w+ = read and write, and also create the file if it does not already exist, overwrites contents
a+ = read and write, create file if doesn't exist and start writing at END

Please vote on the usefulness of this diary entry so other people will know if it is worth their time to read :)

How useful was this diary entry? Avg Surfer Rating: 3.89 (164)

[back]WB01624_.gif (281 bytes) 02/15/00 "Using flock to protect files from corruption" Next[next]

PHP Diary | PHP Housekeeping | PHP Scripts | TD Scripts.com

Copyright 2000 php-scripts.com Last Modified 07/7/00 01:51