How can a captcha be implemented using PHP?

A common method for implementing captcha in PHP is to generate image captchas using the GD library or ImageMagick library. Here is a simple example code:

<?php
session_start();

$width = 100;
$height = 30;

$image = imagecreatetruecolor($width, $height);

$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);

imagefill($image, 0, 0, $bgColor);

$code = substr(md5(uniqid()), 0, 5);

$_SESSION['captcha'] = $code;

imagestring($image, 5, 10, 5, $code, $textColor);

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

In the given code, a black background image of size 100×30 is created first. Then a 5-digit random captcha is generated, stored in the session, and drawn onto the image.

Finally, the generated verification code image will be output to the browser in PNG format. This method allows for the implementation of a simple verification code function.

bannerAds