Last updated on April 27th, 2022 at 10:12 am

In this tutorial we are going to see how to lock a text file before writing data using php. When a developer uses text file instead of SQL or MYSQL or any other database for their website, many will come across issues due to simultaneous insertion of data by their users.

Text file doesn’t have any logic of locking or preventing overwrite unlike databases. So in order to prevent issues like overwriting or file getting corrupted we can implement a lock of the file using PHP and write the data. This will make sure that when a different process / user try to write data to the same file they will see it is locked and have to wait till the lock is released.

<?php
$file = fopen('file.txt', 'w');
if(flock($file, LOCK_EX | LOCK_NB)){
    echo 'Got lock, continue writing to file';
    // Code to write to file gave a sleep condition to simulate writing to the file
        sleep(5);
    //Unlock the file once writing is done
    flock($file,LOCK_UN);
}else{
    echo 'File is locked by another process, aborting writing';
    // Couldn't obtain the lock immediately
}
fclose($file);
?>

In Command-line

These file locking scripts becomes more useful through command lines rather than using them in websites through browsers.

For example when a specific cronjob is running if you don’t want users to use the file then this script comes handy.

First run the script to get the lock

Then in parallel run it again in a different ssh session to see similar message like below

Leave a Reply

Your email address will not be published. Required fields are marked *