Skip to content

Instantly share code, notes, and snippets.

@asaelko
Created June 20, 2016 11:37
Show Gist options
  • Save asaelko/1025cd27ab9478fc20f5232c389be302 to your computer and use it in GitHub Desktop.
Save asaelko/1025cd27ab9478fc20f5232c389be302 to your computer and use it in GitHub Desktop.
<?php
function write_php_ini($array, $file)
{
$res = array();
foreach ($array as $key => $val) {
if (is_array($val)) {
$res[] = "[$key]";
foreach ($val as $skey => $sval) $res[] = "$skey = " . (is_numeric($sval) ? $sval : '"' . $sval . '"');
} else $res[] = "$key = " . (is_numeric($val) ? $val : '"' . $val . '"');
}
safe_file_rewrite($file, implode("\r\n", $res));
}
function safe_file_rewrite($fileName, $dataToSave)
{
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment