What are the best practices for generating and returning graphics in PHP, specifically for Captcha generation?

Generating and returning graphics in PHP, specifically for Captcha generation, can be achieved by using the GD library to create the image and outputting it as a PNG or JPEG file. It is important to set the correct content type header before outputting the image to ensure it is displayed correctly in the browser.

<?php
// Start a session to store the Captcha code
session_start();

// Generate a random Captcha code
$captcha_code = substr(md5(mt_rand()), 0, 6);

// Store the Captcha code in the session
$_SESSION['captcha_code'] = $captcha_code;

// Create a blank image with dimensions for the Captcha text
$image = imagecreate(200, 50);

// Set the background color
$bg_color = imagecolorallocate($image, 255, 255, 255);

// Set the text color
$text_color = imagecolorallocate($image, 0, 0, 0);

// Write the Captcha code on the image
imagestring($image, 5, 50, 20, $captcha_code, $text_color);

// Set the content type header
header('Content-type: image/png');

// Output the image as PNG
imagepng($image);

// Free up memory
imagedestroy($image);
?>