What if I file_get_contents()
a file while it is being processed by file_put_contents()
. Will the file get the past contents of the file or the current contents that are not yet finished writing?
Asked
Active
Viewed 98 times
2

DonCallisto
- 29,419
- 9
- 72
- 100

Mark Lopez
- 770
- 1
- 6
- 10
-
what do you mean with "while"? Concurrent process/threads or ... ? – DonCallisto Feb 25 '14 at 09:20
2 Answers
0
file_get_contents()
will read the incomplete file, because file_put_contents()
writes the file buffered. You will have this effect especially for large files.
Edit: Note (because it came up in another comment):
You can use the LOCK_EX flag to apply a lock.
file_put_contents ( $filename, $content, LOCK_EX );
$content = file_get_contents ( $filename, LOCK_EX );

Kenyakorn Ketsombut
- 2,072
- 2
- 26
- 43
-
Yes very small files will be written atomically. But in general, these functions are not atomic. – Kenyakorn Ketsombut Feb 25 '14 at 09:24
-1
If one process tries to access a file while another is writing to it, the one reading will be locked until the write is complete - this is why if you're using file-based sessions and have PHP files like:
// a.php:
session_start();
sleep(60);
// b.php:
session_start();
echo "Hi!";
Then if you load a
followed by b
in different browser tabs, b
will hang until a
has finished. This is because a
has locked the session file, and b
is waiting for the lock to be released.
The same applies to file_get_contents
/file_put_contents
.

Niet the Dark Absol
- 320,036
- 81
- 464
- 592
-
This is wrong. There is no locking that applies to file_get_contents/file_put_contents. – Kenyakorn Ketsombut Feb 25 '14 at 09:25
-
-
@djay check the docs http://au1.php.net/file_put_contents and look for LOCK_EX – Kenyakorn Ketsombut Feb 25 '14 at 09:30