读取文件时如何删除或编辑 PHP 中的文件


How do you delete or edit a file in PHP when it is being read?

假设PHP上有一个文件。不断读取文件。我想先阻止用户访问该文件,然后再删除或编辑该文件。我该怎么做?

请参考这个答案。PHP 中的文件锁定

这涵盖了锁定部分。但是,要访问该文件,您需要执行循环,直到释放锁。下面是一个示例算法。

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