Skip to content

Instantly share code, notes, and snippets.

@Geri-Borbas
Last active August 29, 2015 13:57
Show Gist options
  • Save Geri-Borbas/9380732 to your computer and use it in GitHub Desktop.
Save Geri-Borbas/9380732 to your computer and use it in GitHub Desktop.
Writes a file without the worry on simultaneous file writings.
/**
* 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