Last active
August 29, 2015 13:57
-
-
Save Geri-Borbas/9380732 to your computer and use it in GitHub Desktop.
Writes a file without the worry on simultaneous file writings.
This file contains hidden or 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
/** | |
* Writes a file without the worry on simultaneous file writings. | |
* | |
* @param mixed $data - Data to put into the file. | |
* @param string $filePath - Path to the file to put data into. | |
* @param number $timeOut - The maximum time (milliseconds) until method attempts to write file (defaults to 1000). | |
* @return bool - Returns true if data has been written. | |
*/ | |
function writeDataToFileSafely($data, $filePath, $timeOut = 1000) | |
{ | |
$interval = 10; // milliseconds | |
$elapsed = 0; | |
$success = false; | |
while($success === false && $elapsed < $timeout) | |
{ | |
$success = file_put_contents($filePath, $data, LOCK_EX); | |
usleep(interval * 1000); // to microseconds | |
$elapsed += $interval; | |
} | |
return $success; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment