-
Notifications
You must be signed in to change notification settings - Fork 65
/
safe_file_rewrite.php
38 lines (32 loc) · 1.04 KB
/
safe_file_rewrite.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
if (!function_exists('safe_file_rewrite')) {
/**
* Safely rewrites a file
*
* @param string $fileName A path to a file
*
* @param string $dataToSave the string to rewrite the file
*/
function safe_file_rewrite($fileName, $dataToSave)
{
if (!is_writable($fileName)) {
throw new Exception("$fileName is not writeable.");
}
if ($fp = fopen($fileName, 'w')) {
$startTime = microtime(TRUE);
do {
$canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if (!$canWrite) {
usleep(round(rand(0, 100) * 1000));
}
} while ((!$canWrite) and ((microtime(TRUE) - $startTime) < 5));
//file was locked so now we can store information
if ($canWrite) {
fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
}