Erik's blog

Code, notes, recipes, general musings

PHP atomic write function

with 4 comments


An atomic write function for those who appreciate the convenience of file_put_contents(), but need an atomic operation.  Please leave a comment if you have a more convenient and/or efficient solution.

Update (5/31/11):

Now using flock, as recommended by Petr and Hayden in their comments below, to avoid race condition. Thanks for the help!

Source code:

function atomic_put_contents($filename, $data)
    // Copied largely from
    $fp = fopen($filename, "w+");
    if (flock($fp, LOCK_EX)) {
        fwrite($fp, $data);
        flock($fp, LOCK_UN);

Example usage:

$content = 'some content';

atomic_put_contents('path/file.ext', $content);

//creates file called path/file.ext containing 'some content'

Written by Erik

October 26, 2008 at 1:58 am

Posted in code

Tagged with

4 Responses

Subscribe to comments with RSS.

  1. Is a good solution?
    Function “exec” ordinarily not available on a web-hostings, but PHP have atomic and fast function and this is rename which atomic work only the same partition. Not only write to file must be atomic, but read too. check

    Petr Kramář

    June 7, 2009 at 10:26 pm

    • thanks, Petr! I don’t have any experience w/ flock, but I’ll take a look at it. I heard writing and mv-ing a file was a simple, effective method for manipulating a file atomically, and it’s worked for my humble needs, but I’d prefer to use something more standard.


      June 12, 2009 at 10:02 am

  2. This code has race conditions. It is possible that the file $tmp_path will be removed by another process after line 10, but before line 13. If you truly need atomicity, use flock() as Petr suggested.


    April 13, 2011 at 2:57 pm

    • Thanks, Hayden. I’ve updated the function to use flock.


      May 31, 2011 at 9:05 pm

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: