Motivation:

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:

[sourcecode language=“php”]

function atomic_put_contents($filename, $data) { // Copied largely from http://php.net/manual/en/function.flock.php $fp = fopen($filename, “w+”); if (flock($fp, LOCK_EX)) { fwrite($fp, $data); flock($fp, LOCK_UN); } fclose($fp); }

[/sourcecode]

Example usage:

[sourcecode language=“php”]

$content = ‘some content’;

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

//creates file called path/file.ext containing ‘some content’

[/sourcecode]