Problems with file recording PHP files

On a PHP webpage, I open the file in write mode, reading and deleting the first line and closing the file. (The file has 1000 lines)

Now, what is the problem, if 100 users are connected to this page, everyone will open this file in write mode, and then try to write it after deleting the first line. Will there be any deadlocks in this situation?

For your information we use a Windows server with an IIS server and PHP5.
Thanks in advance for your help.

+3
source share
2 answers

Use flock to grant file access to only one user at a time.

But don't forget to release the fclose file lock

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 the file for 3 seconds, so consider our script guide as asynchronous). You will see something like this:

First instance:

  • File was locked in 1302788738. Exclusive access was granted to the recording.
  • File Lock was released in 1302788741

Secondly:

  • File was locked in 1302788741 . Exclusive Recording Access Provided
  • File Lock was released at 1302788744

Note that the second instance was waiting to release the file lock first.

If this does not meet your requirements, well ... try inventing another solution, for example: the user can read the file, then he edits one line and saves it as a temporary line, the other user saves his temporary file, etc., and after that as you all users have released file locking, you create a new file as a patch of all temporary files against each other (use save mtime files to determine which file should be stratified by another) ... Something like this .... maybe. .. I am not an expert in such problems unfortunately, just my guess about how you can do this.

+6
source

Use a file lock or database that allows simultaneous access. Otherwise, you will have problems.

+2
source

All Articles