What are the best practices for creating and displaying captchas in PHP?

To create and display captchas in PHP, it is important to use a combination of random characters, distortion techniques, and validation checks to ensure security. Captchas help prevent automated bots from submitting forms and protect against spam attacks on websites.

<?php
session_start();

$randomString = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"), 0, 6);
$_SESSION['captcha'] = $randomString;

$im = imagecreatetruecolor(100, 30);
$bgColor = imagecolorallocate($im, 255, 255, 255);
$textColor = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 100, 30, $bgColor);
imagettftext($im, 15, 0, 10, 20, $textColor, 'arial.ttf', $randomString);

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