tags:

views:

65

answers:

2

Hi!

I am making a simple page load counter by storing the current count in a file. This is how I want to do this:

  1. Lock the file (flock)
  2. Read the current count (fread)
  3. Increment it (++)
  4. Write new count (fwrite)
  5. Unlock file/close it (flock/fclose)

Can this be done without losing the lock?

As I understand it, the file can't be written to without losing the lock. The only way I have come up with to tackle this, is to write a character using "r+" mode, and then counting characters.

+2  A: 

I believe you can achieve this using flock. Open a pointer to your file, flock it, read the data, write the data, then close (close automatically unlocks).

http://php.net/flock

adam
Yeah I know about flock, but not how to keep the lock when I write.
Znarkus
The lock is maintained until you either unlock, close the file or the script terminates.
adam
+1  A: 

As said, you could use FLock. A simple example would be:

//Open the File Stream
$handle = fopen("file.txt","r+");

//Lock File, error if unable to lock
if(flock($handle, LOCK_EX)) {
    $count = fread($handle, filesize("file.txt"));    //Get Current Hit Count
    $count = $count + 1;    //Increment Hit Count by 1
    ftruncate($handle, 0);    //Truncate the file to 0
    fwrite($handle, $count);    //Write the new Hit Count
    flock($handle, LOCK_UN);    //Unlock File
} else {
    echo "Could not Lock File!";
}

//Close Stream
fclose($handle);
Jamza
Thank you, ftruncate was what I was looking for!
Znarkus
ftruncate didn't work as expected, but `rewind` did the trick
Znarkus