3

I have created a script to generate a sequence made up of number and letter like A-0045-20170502.My problem is how to lock the file so that in concurrent usage of that file only one user can can edit before the others.

function sequence(){ $letter = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];

    $content = file_get_contents("seq_file");
    $content = file_get_contents("seq_file") + 1 ;
    $letter_number = file_get_contents("letter_number");

    if ($content ==9999){

        file_put_contents("seq_file",0);
        $content = 0 ;
        $letter_number = $letter_number + 1 ;
        file_put_contents("letter_number",$letter_number);
    }
    file_put_contents("seq_file",$content);

       return   sprintf("%s-%05d-%s",$letter[$letter_number],$content,date("Ymd",strtotime("now"))); // A-00522-20170205
}



if(file_exists("seq_file") &&  file_exists("letter_number")){
    $seq = sequence();
} else {
    file_put_contents("letter_number",0);
    file_put_contents("seq_file",0);
    $seq = sequence();

}

1 Answers1

3

You can use the flock function for this. When you are done reading/writing, make sure to release your lock using flock($file_handle, LOCK_UN).

Example from the PHP-website:

<?php

$fp = fopen("/tmp/lock.txt", "r+");

if (flock($fp, LOCK_EX)) {  // acquire an exclusive lock
    ftruncate($fp, 0);      // truncate file
    fwrite($fp, "Write something here\n");
    fflush($fp);            // flush output before releasing the lock
    flock($fp, LOCK_UN);    // release the lock
} else {
    echo "Couldn't get the lock!";
}

fclose($fp);

?>
Pieter De Clercq
  • 1,951
  • 1
  • 17
  • 29