Created
November 11, 2015 16:16
-
-
Save dontfreakout/7e2d584174cf01a187cd to your computer and use it in GitHub Desktop.
PHP Atomic file put content
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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