swapfile
swapfile

Reputation: 417

Create Random PNG in PHP and Output in html

I have a php file "builder.php" which is generating a random png file with imagepng and imagecopyresized. Every reload is generating a different png. I want to display a few of the generated pics in html to decide which is good and which not. The good ones should be saved as png an the bad ones not.

builder.php

<?php

...
$mix=getmix($link);
header('Content-Type: image/png');

    $base = imagecreatefrompng("base.png");
    $logo = imagecreatefrompng("fs_logo_line.png");
    $nr1 = imagecreatefrompng("template_women_number_1.png");

    $pos1 = imagecreatefrompng($mix['jhjk']['img']);
    $pos2 = imagecreatefrompng($mix['hkjh']['img']);
    
    imagecopyresized($base,$pos1,0, 0, 0, 0, 501, 697, 501, 697);
    imagecopyresized($base,$pos2,451, 0, 0, 0, 485, 697, 485, 697);
    imagecopyresized($base,$nr1,20, 20, 0, 0, 39, 38, 39, 38);
    imagecopyresized($base,$logo,0, 1136, 0, 0, 1200, 64, 1200,64);

    imagepng($base);
    imagedestroy($base);
    imagedestroy($logo);
?>

$mix is a variable array with sql data. With every reload $mix will be shuffled.

html page where the images should be loaded:

<!DOCTYPE html>
  <head>
  </head>
  <body>
    <img src="builder.php" />
    <img src="builder.php" />
  </body>
</html>

The problem is that it seems that the builder.php is just loaded only one time and displays the same pic twice. If I load builder.php standalone it generates a new pic every reload. I know I could work with get/post to change the builder.php but in this case there's no need, or?

Upvotes: 0

Views: 140

Answers (1)

Jay Blanchard
Jay Blanchard

Reputation: 34426

Think about it for a second - at the time PHP runs on the server there is only one builder.php requested and cached. One way to fix this is to add a random string to your image source string:

<img src="builder.php?t=<?php echo uniqid(); ?>" />

Now each call to builder.php is unique and should return a random image.

Upvotes: 2

Related Questions