I'm using file_get_contents() to get the contents of a file, BUT I need to be sure that the file doesn't change while file_get_contents() is reading the contents of the file.

I'm not sure if file_get_contents() will ensure that the file contents don't get changed ( another script fwrites() to the file ) while file_get_contents() is doing its thing, or if I need to use a lock file to ensure this doesn't happen.

Anyone know if I need to use a lock file, or will I be fine just calling file_get_contents()?

    you should be fine. Unless the file is many MB in size, it should take less than 1 second to get the contents of the file.

    If you really wanted, you could lock the file at first, then unlock it when you're done, but it wouldn't make a difference unless you're working with something like a flat-file database.

    ~Brett

      They're cached pages. It's important I don't read in half of the file and display that, that wouldn't be very nice to the user :-)

      The files are small, no larger than 150kb... but a lot can happen in a second :-)

        You can certainly use file locking for this purpose, but bear in mind that you can't lock a file which doesn't exist.

        Also, locking semantics differ between operating systems; Unix locks aren't mandatory so they don't stop another process from messing the file up, they just stop it from taking its own lock. They do nothing against a file being deleted.

        Depending on how often you're having this problem, you could use a separate lock file, or lock the files themselves. If you do the latter, you probably need to open them read/write if you intend to write to them, and then acquire a write lock before you truncate the file. Or something.

        Mark

          you should always lock your files. you never know what could happen.

          if my employer were to say i didn't need to bother but a month down the road something breaks i'm the one to blame. if it's an important site that alot of people vist then you better lock that file. when i did some C++ for some backing company here and we needed to work with thier database i had to lock and unlock everything that i did.

            I realize that files should be locked, the question is more of:
            Does file_get_contents()/the actual filesystem perform locking while reading the file on its own, or do I need handle the locking myself?

            I'd be locking the file using a seperate lock file, so I don't have to worry about the mandatory/advisory lock business as my script would be the only thing dealing with the files/locks.

              Handle it yourself. I don't think PHP would have included the function if it handled locking on its own. But I coudl be wrong.

              ~Brett

                Write a Reply...