CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is widely used to verify users' identities, typically by requiring users to recognize characters or images to prevent automated bot activities. In this article, we'll guide you through the process of generating CAPTCHA images with PHP and displaying them on your webpage.
First, we need to create a PHP file named captcha.php and ensure the file extension is .php.
In the PHP script, we'll define some variables to set the dimensions of the CAPTCHA image, the number of characters, and the possible characters for the CAPTCHA. Here's a code example:
$width = 120; // CAPTCHA image width
$height = 40; // CAPTCHA image height
$characters = 4; // Number of CAPTCHA characters
$possibleChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
Next, we create a blank image and set some basic attributes, such as background color, text color, and font. Here's the code:
$image = imagecreatetruecolor($width, $height);
$backgroundColor = imagecolorallocate($image, 255, 255, 255); // Background color: white
$textColor = imagecolorallocate($image, 0, 0, 0); // Text color: black
imagefill($image, 0, 0, $backgroundColor);
$font = 'path/to/your/font.ttf'; // Font file path
Now, we need to randomly generate characters for the CAPTCHA and draw them on the image. PHP provides random number generation functions, which we can use to select characters from our set. Here’s an example:
$captcha = '';
for ($i = 0; $i < $characters; $i++) {
$randomChar = $possibleChars[rand(0, strlen($possibleChars) - 1)];
$captcha .= $randomChar;
$x = ($width / $characters) * $i + 10; // Character position
$y = $height / 2 + 15; // Text vertical alignment
imagettftext($image, 20, 0, $x, $y, $textColor, $font, $randomChar);
}
To verify the CAPTCHA later, we need to store the generated CAPTCHA in the PHP session. Here’s the code:
session_start();
$_SESSION['captcha'] = $captcha;
Finally, we need to set the appropriate headers and output the CAPTCHA image to the user:
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
By following these steps, we've successfully created a simple CAPTCHA system. Each time the page is refreshed, the user will see a new CAPTCHA image, ensuring enhanced security by preventing automated attacks. In practical applications, you can compare the user's input with the CAPTCHA stored in the session to verify their identity.
This is a basic PHP CAPTCHA implementation, and you can extend and optimize it further based on your needs.