【问题标题】:How do you delete or edit a file in PHP when it is being read?在 PHP 中读取文件时如何删除或编辑文件?
【发布时间】:2016-04-21 01:30:00
【问题描述】:

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

【问题讨论】:

    标签: php file locking mutual-exclusion


    【解决方案1】:

    请参考这个答案。 file locking in 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 2017-03-02
      • 1970-01-01
      相关资源
      最近更新 更多