Skip to content

Instantly share code, notes, and snippets.

@SamWM
Created January 8, 2010 10:46
Show Gist options
  • Save SamWM/271973 to your computer and use it in GitHub Desktop.
Save SamWM/271973 to your computer and use it in GitHub Desktop.
Atomic Write File
// code adapted from http://uk.php.net/manual/en/function.file-put-contents.php#82934
// a subfolder called 'cache' within the directory that this code is in
define("FILE_PUT_CONTENTS_ATOMIC_TEMP", dirname(__FILE__).DIRECTORY_SEPARATOR."cache");
// give owner, group and public write access after writing the file
define("FILE_PUT_CONTENTS_ATOMIC_MODE", 0777);
function file_put_contents_atomic($filename, $content) {
// generate a temporary file
$temp = tempnam(FILE_PUT_CONTENTS_ATOMIC_TEMP, 'temp');
// try to open temporary file (for writing, as binary)
if (!($f = @fopen($temp, 'wb'))) {
// try again if tmpname didn't work
$temp = FILE_PUT_CONTENTS_ATOMIC_TEMP.DIRECTORY_SEPARATOR.uniqid('temp');
if (!($f = @fopen($temp, 'wb'))) {
trigger_error("file_put_contents_atomic() : error writing temporary file '$temp'", E_USER_WARNING);
return false;
}
}
// write content to temporary file
fwrite($f, $content);
// close the file
fclose($f);
// try to rename the temp file to the new file
if (!@rename($temp, $filename)) {
// delete the old file
@unlink($filename);
// rename the temp file
@rename($temp, $filename);
}
// give file appropriate permissions
@chmod($filename, FILE_PUT_CONTENTS_ATOMIC_MODE);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment