PHP file_put_contents and Concurrency

I recently received a question regarding PHP’s file_put_contents function and possible issues with concurrency for simultaneous write requests. After a bit of research and I uncovered a good bit of speculation – most of it suggesting that concurrency would, in fact, be an issue.

That answer didn’t feel right to me so I set up a simple test.

First, I wrote a PHP script to write to a file using the file_put_contents function:
<?php
file_put_contents('test_file.txt','data'."\n",FILE_APPEND);
echo strtotime('now');

Then I made an HTML page loaded with a thousand iframes to simulate a thousand simultaneous requests. It looked something like this:
<iframe src ="test_write_file.php" width="100%" height="25"><p>iframe</p></iframe>
<iframe src ="test_write_file.php" width="100%" height="25"><p>iframe</p></iframe>
<iframe src ="test_write_file.php" width="100%" height="25"><p>iframe</p></iframe>
<snip> x1000

Results

Three page loads took an average of 118.6 seconds to fully execute, and all 1,000 lines were written to the file each time. My observation is that overlapping requests were not discarded, but were queued pending lock release on the target file to be executed at the earliest opportunity.

While my definition of concurrency may not be accurate, I will go so far as to say that practically speaking, concurrency is not an issue for simultaneous write requests using PHP’s file_put_contents function.


Comments are closed.