search

Home  >  Q&A  >  body text

Does php have a function to determine whether a file is open?

Like the question, if you sometimes need to add content to a file, how can you ensure that what you write will not be opened and written in by another person?

What I want is to generate something randomly before the writing operation starts, and then delete it after the operation is completed;

淡淡烟草味淡淡烟草味2794 days ago640

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-05-16 13:00:28

    File Lock

    <?php
    
    $fp = fopen("/tmp/lock.txt", "r+");
    
    if (flock($fp, LOCK_EX)) {  // 进行排它型锁定
        ftruncate($fp, 0);      // truncate file
        fwrite($fp, "Write something here\n");
        fflush($fp);            // flush output before releasing the lock
        flock($fp, LOCK_UN);    // 释放锁定
    } else {
        echo "Couldn't get the lock!";
    }
    
    fclose($fp);
    
    ?>

    From : http://php.net/manual/zh/func...

    reply
    0
  • Cancelreply