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
  • 29,419
  • 9
  • 72
  • 100
Mark Lopez
  • 770
  • 1
  • 6
  • 10

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
  • 2,072
  • 2
  • 26
  • 43
-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