Hello, is it possible to check to see if a text file is already open in PHP or not? Also, if the file is open I want my script to wait a few seconds before checking whether the file is open again. Can anyone give me some ideas on how to do this?

Thanks,
Jon.

    $fp = fopen('/some/path/file.txt', 'r');
    
    if ($fp)
    {
        echo 'file is open';
    }
    else
    { 
        echo 'file is not opened, or not found.';
    }
    

    you can use flush() and sleep() to pause it from checking (delaying it)..

      Sorry, I didn't word that to well. On my website people can write messages to a text file. Sometimes though I can get quite a few poeple on the site and I want to ensure that you don't get one person writting to the file at the same time as someone else. I figured I could do this by testing to see if the file is already open, by another user, if it is then I can pause the script (using sleep()) and then try again. As far as I can see the script you posted will only tell you if the file is open in the current instance of the script, if that makes sence.

      Is there a better way of doing this?

        ok i see what you mean now.

        flock

        have a look at the example as well..

          Thanks, I think that's what I'm looking for. Can't be certain though as it's very difficult to test.

          Thanks again,
          Jon.

            Write a Reply...