Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

php - Read and write to a file while keeping lock

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    rewind($handle);           //Set write pointer to beginning of file
    fwrite($handle, $count);    //Write the new Hit Count
    flock($handle, LOCK_UN);    //Unlock File
} else {
    echo "Could not Lock File!";
}

//Close Stream
fclose($handle);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...