I have read php's manual page on the 'file_get_contents' function which does not state anything about how 'file_get_contents` behaves with respect to php's file locking. However in the comment section user Chris suggests that
file_get_contents does not normally respect PHP's flock locking, i.e. advisory locking.
You can workaround this with some extra code to request a shared lock, like...
<?php
$tmp = fopen($path, 'rb');
@flock($tmp, LOCK_SH);
$contents = file_get_contents($path);
@flock($tmp, LOCK_UN);
fclose($tmp);
?>
which I have tested with success. I have also tested that even though a file has been locked with flock()
exclusively LOCK_EX
it was possible to have another php process read the file via file_get_contents
as the comment would have suggested.
However, and that is mainly why I ask for information, I have read a webpage titled "Reading locked files in PHP", which claimed the following with regards to file_get_contents
and file locking.
Reading a locked file with file_get_contents()
This is one the worst way to read a file while it is locked and modified, because:
- file_get_contents() will return an empty string (like in "")
- filesize() will return the actual number of bytes written to the file
I this claim correct? I run some tests, locking a file exclusively and constantly writing to it, while using file_get_contents
in another php process to read the file and have not experienced the behaviour that as stated above
file_get_contents() will return an empty string (like in "")
Is it true in general that, php's file_get_contents
does not care anything about the advisory file locking.
Also, am I assuming correctly that the claims made in the webpage of the empty string returned by file_get_contents is empty "", is only true if the file is empty, or temporarily empty (while being modified) but not generally empty (only for the reason of the file being flock()
ed)?
file_get_contents
would henceforth return necessarily an empty "", because of a file lock. Without a file lock the data read viafile_get_contents
might not be reliable maybe (as no concurrent editions might occur) but I should not assume thatfile_get_contents
would kind of check a file lock implicitly and return an empty string? (as was indicated in the second resource linked in the question), correct? – Crash