How can PHP be used to create a simple Captcha encryption for web forms?

To create a simple Captcha encryption for web forms using PHP, you can generate a random string as the Captcha code, store it in a session variable, and display it in an image on the form. When the form is submitted, you can check if the entered Captcha code matches the one stored in the session variable to verify that the user is human.

<?php
session_start();

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

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

// Create an image with the Captcha code
$im = imagecreatetruecolor(100, 30);
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 0);
imagestring($im, 5, 10, 5, $captchaCode, $textcolor);

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