Read and write to a file while keeping lock

前端 未结 3 689
半阙折子戏
半阙折子戏 2020-12-03 22:10

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 c
3条回答
  •  情歌与酒
    2020-12-03 22:27

    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);
    

提交回复
热议问题