'Make sure imagepng has written the file on the server

I have a function which adds text under a existing qr-code image. In some cases the return is faster than the server has written the image on the filesystem, so that other function got issues.

How can I make sure that everything is done before I return the path to the image? At the moment I am trying to use a while-loop, but I am also really unhappy with it. That causes also timeouts and crashes on my server (no idea why).

function addTextToQrCode($oldImage, $text)
{
    $newImage = $oldImage;
    $newImage = str_replace(".png", "_original.png", $newImage);
    copy($oldImage, $newImage);

    $image = imagecreatefrompng($oldImage);
    $black = imagecolorallocate($image, 0, 0, 0);
    $fontSize = 20;
    $textWidth = imagefontwidth($fontSize) * strlen($text);
    $textHeight = imagefontheight($fontSize);
    $x = imagesx($image) / 2  - $textWidth / 2;
    $y = imagesy($image) - $textHeight - 3;
    imagestring($image, 5, $x, $y, $text, $black);

    $filePath = "/qrCodes/qrcode".$text.'.png';
    imagepng($image, $filePath);
    
    while(!$this->checkIfNewQrCodeIsOnFileSystem($filePath)){
            $this->checkIfNewQrCodeIsOnFileSystem($filePath);
        }
     return $filePath;
    
}

 function checkIfNewQrCodeIsOnFileSystem($filePath) {
        if (file_exists($filePath)) {
            return true;
        } else {
            return false;
        }
    }
php


Solution 1:[1]

Check only imagepng(). The solution i would prefer.

function addTextToQrCode($oldImage, $text)
{
    $newImage = $oldImage;
    $newImage = str_replace(".png", "_original.png", $newImage);
    copy($oldImage, $newImage);

    $image = imagecreatefrompng($oldImage);
    $black = imagecolorallocate($image, 0, 0, 0);
    $fontSize = 20;
    $textWidth = imagefontwidth($fontSize) * strlen($text);
    $textHeight = imagefontheight($fontSize);
    $x = imagesx($image) / 2  - $textWidth / 2;
    $y = imagesy($image) - $textHeight - 3;
    imagestring($image, 5, $x, $y, $text, $black);

    $filePath = "/qrCodes/qrcode".$text.'.png';
    if (imagepng($image, $filePath) === true) {
       return $filePath;
    } 
    
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1