I'm using the following code to create and append data to a tar-archive in PHP. The problem is that phar does not use an exclusive lock on the tar-file causing problem when I have atomic writes to the same file.
function phar_put_contents($fname, $archive, $data) {
$i=0;
do {
$fp = @fopen($archive.'.lock', 'w');
if(!$fp) {
usleep(25);
continue;
}
if(flock($fp, LOCK_EX)) {
try{
$myPhar = new PharData($archive.'.tar',0);
$myPhar[$fname] = $data;
$myPhar->stopBuffering();
flock($fp, LOCK_UN) && @fclose($fp);
@unlink($archive.'.lock');
return true;
} catch (Exception $e) {
error_log($e->getMessage()." in ".$e->getFile().":".$e->getLine(),0);
unset($e);
@flock($fp, LOCK_UN) && @fclose($fp);
}
}
} while ($i++<8);
return false;
}
Using a look file seems to be a "good" solution but it's not optimal since my archives gets currupted quite frequently.