Search code examples
phpfilesystemsunlink

What happens if you delete a file in PHP while the web server is serving the file to the website visitor


unlink("cache/data.xml");

I feel that this may generate an error at times when sever might be reading and serving it to the visitor.

how to safely delete the file so script will continue to wait until the read lock from the web server is released if any and then continue deleting the file or how it works out there?

Thanks


Solution

  • This will depend on the specific system this is running on, but the man page for the UNIX unlink function (which the PHP unlink function very likely relies on internally) says this:

    The unlink() function removes the link named by path from its directory and decrements the link count of the file which was referenced by the link. If that decrement reduces the link count of the file to zero, and no process has the file open, then all resources associated with the file are reclaimed. If one or more process have the file open when the last link is removed, the link is removed, but the removal of the file is delayed until all references to it have been closed.

    In other words, the process reading the file can continue to do so, even while the file is being deleted.