-1

Supposing that there is a file on PHP. The file is constantly being read. I want to stop users from accessing the file first, then delete or edit the file. How can I do this?

Long Le
  • 404
  • 5
  • 18

1 Answers1

0

Please refer to this answer. file locking in php

That covers the locking part. However, to access the file you need to do a loop until the lock is released. Here is a sample algorithm.

   define(MAX_SLEEP, 3); // Decide a good value for number of tries
   $sleep = 0; // Initialize value, always a good habit from C :)
   $done = false; // Sentinel value 
   $flock = new Flock; // You need to implement this class
    do {
        if (! $flock->locked()) { // We have a green light
            $flock->lock(); // Lock right away

            //DO STUFF;

            $flock->unlock(); // Release the lock so others can access
            $done = true; // Allows the loop to exit

        } else if ($sleep++ > MAX_SLEEP) { // Giving up, cannot write
            // Handle exception, there are many possibilities:
            //     Log exception and do nothing (definitely log)
            //     Force a write 
            //     See if another process has been running for too long
            //     Check for timestamp of the lock file, maybe left behind after a reboot
        } else {
            sleep(SLEEP_TIME);
        }
    } while(! $done);
Community
  • 1
  • 1
chelista
  • 73
  • 7