如何使用php锁定打开的文本文件

时间:2017-05-23 22:25:42

标签: php

我创建了一个脚本来生成一个由数字和字母组成的序列,如A-0045-20170502.我的问题是如何锁定文件,以便在同时使用该文件时只有一个用户可以在其他用户之前编辑

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 个答案:

答案 0 :(得分:3)

您可以使用flock功能。完成阅读/写作后,请务必使用flock($file_handle, LOCK_UN)释放锁定。

来自PHP网站的示例:

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

?>