2

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?

DonCallisto
  • 28,203
  • 8
  • 66
  • 94
Mark Lopez
  • 552
  • 1
  • 4
  • 8

2 Answers2

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
  • 1,983
  • 2
  • 23
  • 42
-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
  • 311,322
  • 76
  • 447
  • 566