In a PHP webpage, Im opening a file in write mode, reading and than deleting the first line and closing the file. (The file has 1000's of lines)
Now, what the problem is, if there are like 100 users connected to that page, all will be opening that file in write mode and than try to write it after deleting the first line. Will there be any deadlocks in this situation?
For your information, we are using Windows server with IIS server and PHP5.
Thanks in advance for your help.
Use flock to grant access to file only for one user at a time.
But don't forget release your file lock by fclose
Update. Consider this code:
<?php
$start = time();
echo 'Started at '.$start.'<br />';
$filename = 'D:\Kindle\books\Brenson_Teryaya_nevinnost__Avtobiografiya_66542.mobi';
$fp = fopen($filename, 'w+') or die('have no access to '.$filename);
if (flock($fp, LOCK_EX)) {
echo 'File was locked at '.time().'. Granted exclusive access to write<br />';
}
else {
echo 'File is locked by other user<br />';
}
sleep(3);
flock($fp, LOCK_UN);
echo 'File lock was released at '.time().'<br />';
fclose($fp);
$end = time();
echo 'Finished at '.$end.'<br />';
echo 'Proccessing time '.($end - $start).'<br />';
Run this code twice (it locks file for 3 seconds, so let's consider our manual script run as asynchronous). You will see something like this:
First instance:
Second:
Notice, that second instance waited for first to release file lock.
If it does not comply your requirements, well... try to invent other solution like: user can read file, then he edit one line and save it as temporary, other user saves his temporary file and so on and once you have all users released file lock, you compose new file as patch of all temporary files on each other (use save files mtime to define which file should stratify other one)... Something like this.... maybe... I'm not the expert in this kind of tasks, unfortunately - just my assumption on how you can get this done.
Use file locking, or a database that allows concurrent access. You will get in trouble otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With