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)?
flock is relatively independent of the file operations, you can even use fopen on a locked file. You as developer are responsible for checking/using flock everywhere you require a lock.
But yes in that regard it's true that file_get_contents
has no build-in way to acquire a read lock when reading the file. So the workaround would be the way to go.
file_put_contents
allows you to get a lock for writing though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With