Skip to content
Snippets Groups Projects
Commit b7fce249 authored by Olav Morken's avatar Olav Morken
Browse files

SimpleSAML_Utilities: Add writeFile(), for atomically creating a file.

git-svn-id: https://simplesamlphp.googlecode.com/svn/trunk@1754 44740490-163a-0410-bde0-09ae8108e29a
parent 7870f388
No related branches found
No related tags found
No related merge requests found
...@@ -1995,6 +1995,38 @@ class SimpleSAML_Utilities { ...@@ -1995,6 +1995,38 @@ class SimpleSAML_Utilities {
/* Set the timezone to the default. */ /* Set the timezone to the default. */
date_default_timezone_set($serverTimezone); date_default_timezone_set($serverTimezone);
} }
/**
* Atomically write a file.
*
* This is a helper function for safely writing file data atomically.
* It does this by writing the file data to a temporary file, and then
* renaming this to the correct name.
*
* @param string $filename The name of the file.
* @param string $data The data we should write to the file.
*/
public static function writeFile($filename, $data) {
assert('is_string($filename)');
assert('is_string($data)');
$tmpFile = $filename . '.new.' . getmypid() . '.' . php_uname('n');
$res = file_put_contents($tmpFile, $data);
if ($res === FALSE) {
throw new SimpleSAML_Error_Exception('Error saving file ' . $tmpFile .
': ' . SimpleSAML_Utilities::getLastError());
}
$res = rename($tmpFile, $filename);
if ($res === FALSE) {
unlink($tmpFile);
throw new SimpleSAML_Error_Exception('Error renaming ' . $tmpFile . ' to ' .
$filename . ': ' . SimpleSAML_Utilities::getLastError());
}
}
} }
?> ?>
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment