I have a question about how PHP handles filesystem operations. I'm running this code that depends on a file being created before it gets used, and it feels like when I run the code it becomes a race condition - sometimes the it works, the file is created and php code uses it, sometimes it fails.
So I was wondering how php handles filesystem operations, does it send it off in the background or does it wait till the operation complete?
Yes, unless you open a file handle and then set it to non-blocking mode: stream_set_blocking()
file_put_contents
is equivalent to fopen
, fwrite
, fclose
. fclose
should ensure the file is fully flushed to disk.
PHP should wait until the process is completed. But not knowing how you are implementing the operations it is hard to say. If you can post an example code that you are using that would be helpful so we can help you figure out why it is not working properly.
Year 2013, on my common garden variety linux vps with cpanel, with default settings, with php 5.2.17, file_put_contents always takes ~5ms for short string lengths.
Accidentally 5ms is about the full committed write time of a high quality hdd.
file_put_contents($filename,'abcdefghi...~100chars',FILE_APPEND);
This takes ~5ms consistently. That seems to include 'blocking' and 'flushing'. So for those wondering about speed of file_put_contents, at least 5ms/operation on common servers 2013 04.
If you need speed, for example for some logging, @Matthew Flaschen said:
file_put_contents is equivalent to fopen, fwrite, fclose.
fclose should ensure the file is fully flushed to disk.
Then one needs:
function file_put_contents_fast() {...no fclose...}
But it will take some research to find out what happens if file handles are left open. Php closes them at exit, but does it really do so all the time? Even if it crashes? What happens if a file is left open by php after a crash? etc etc. After 30 minutes of php manual reading and googling, there was no mention of such and its consequences.