A PHP endpoint that outputs only an image should send an image MIME type before any image bytes. Do not send HTML or whitespace before header().
<?php
$image = imagecreatetruecolor(300, 90);
$background = imagecolorallocate($image, 240, 240, 240);
$text = imagecolorallocate($image, 20, 70, 150);
imagefilledrectangle($image, 0, 0, 299, 89, $background);
imagestring($image, 5, 20, 35, 'Dynamic PNG', $text);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>Current example first; the original tutorial examples below are retained and cleaned up for continued learning.
header("Content-Type: image/jpeg");
<?php
header ("Content-Type: image/jpeg");
///// Create the image ////////
$im = @ImageCreate (100,40)
or die ("Cannot Initialize new GD image stream");
$background_color = ImageColorAllocate ($im, 204, 204, 204); // Assign background color
$text_color = ImageColorAllocate ($im, 51, 51, 255); // text color is given
ImageString($im,5,10,10,'PLUS2NET',$text_color); // Random string from session added
ImageJpeg ($im); // image displayed
imagedestroy($im); // Memory allocation for the image is removed.
?>
Output is here<img src=gd-imagestring-demo.php>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Image in PHP</title>
</head>
<body>
<h2 class="text-primary">Generated Image from PHP</h2>
<p class="text-muted">The image below is dynamically generated by test1.php.</p>
<img src="test1.php?time=<?php echo time(); ?>" alt="Dynamic Image" >
</body>
</html>
This code dynamically loads an image generated by the test1.php script. The query string ?time=<?php echo time(); ?> appends a unique timestamp to the image URL using PHP's time() function.<img src="https://www.example.com/dir/test1.php?time=<?php echo time(); ?> alt="Dynamic Image" >
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.