What are best practices for generating and displaying Captcha images in PHP?

To generate and display Captcha images in PHP, it is best practice to use a combination of random characters, distortion techniques, and noise to make it difficult for bots to decipher the text. Additionally, it is recommended to securely store the generated Captcha code in a session variable to validate the user input.

<?php
session_start();

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

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

// Create image with Captcha code
$im = imagecreatetruecolor(100, 30);
$bg_color = imagecolorallocate($im, 255, 255, 255);
$text_color = imagecolorallocate($im, 0, 0, 0);
imagefill($im, 0, 0, $bg_color);
imagestring($im, 5, 10, 5, $captcha_code, $text_color);

// Display Captcha image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>