i come from a java background where there were synchronized blocks:
The \"Synchronized\" keywords prevents concurrent access to a block of code or o
Other people answer with lots of words, but no code. Why don't you try this?
function synchronized($handler)
{
$name = md5(json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,1)[0]));
$filename = sys_get_temp_dir().'/'.$name.'.lock';
$file = fopen($filename, 'w');
if ($file === false) {
return false;
}
$lock = flock($file, LOCK_EX);
if (!$lock) {
fclose($file);
return false;
}
$result = $handler();
flock($file, LOCK_UN);
fclose($file);
return $result;
}
function file_put_contents_atomic($filename, $string)
{
return synchronized(function() use ($filename,$string) {
$tempfile = $filename . '.temp';
$result = file_put_contents($tempfile, $string);
$result = $result && rename($tempfile, $filename);
return $result;
});
}
The above code does an atomic file_put_contents
using a custom "synchronized" function.
Source: https://tqdev.com/2018-java-synchronized-block-in-php