How can multiple simultaneous requests for the same PHP script that generates a PNG image be handled to prevent conflicts?

When multiple simultaneous requests for the same PHP script that generates a PNG image occur, conflicts can arise if the script tries to write the image data to the same file at the same time. To prevent conflicts, you can use file locking mechanisms to ensure that only one request can write to the file at a time, while other requests wait for the lock to be released before proceeding.

<?php
$filename = 'image.png';

$fp = fopen($filename, 'w');
if (flock($fp, LOCK_EX)) {
    // Generate the PNG image here
    imagepng($imageResource, $filename);
    
    flock($fp, LOCK_UN);
} else {
    echo 'Unable to acquire lock for file';
}

fclose($fp);
?>