How can the PHP code for generating CAPTCHA be optimized for better performance and security?
Generating CAPTCHA images in PHP can be optimized for better performance and security by using efficient image generation techniques, such as caching generated images to reduce server load, using secure randomization functions to create unique CAPTCHA codes, and implementing measures to prevent automated bots from bypassing the CAPTCHA.
<?php
session_start();
$randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 6);
$_SESSION['captcha_code'] = $randomString;
$width = 120;
$height = 40;
$image = imagecreate($width, $height);
$background = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);
imagestring($image, 5, 30, 12, $randomString, $textColor);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>