Skip to content

Instantly share code, notes, and snippets.

@dontfreakout
Created November 11, 2015 16:16
Show Gist options
  • Save dontfreakout/7e2d584174cf01a187cd to your computer and use it in GitHub Desktop.
Save dontfreakout/7e2d584174cf01a187cd to your computer and use it in GitHub Desktop.
PHP Atomic file put content
function file_put_contents_atomic($filename, $content) {
$temp = tempnam(FILE_PUT_CONTENTS_ATOMIC_TEMP, 'temp');
if (!($f = @fopen($temp, 'wb'))) {
$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;
}
}
fwrite($f, $content);
fclose($f);
if (!@rename($temp, $filename)) {
@unlink($filename);
@rename($temp, $filename);
}
@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