Image CAPTCHAs are commonly used to protect online forms from automated submissions. They are widely applied in scenarios like user registration, login, and comment posting. In this guide, you’ll learn how to build a simple image CAPTCHA using PHP and the GD graphics library.
Before you begin coding, make sure your PHP environment has the GD extension enabled. GD is a graphics drawing library in PHP that allows dynamic image creation. You can check its availability by running phpinfo().
Create a file named captcha.php. In this script, you will use GD to generate a CAPTCHA image and save the generated code in a PHP session for later verification.
Here’s the code example:
<?php
session_start();
// Generate a random 4-digit code
$code = rand(1000, 9999);
// Store the code in session
$_SESSION['captcha_code'] = $code;
// Create a blank image
$image = imagecreatetruecolor(120, 40);
// Set background color to white
$bg_color = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bg_color);
// Add noise pixels
for ($i = 0; $i < 100; $i++) {
$point_color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($image, rand(0, 120), rand(0, 40), $point_color);
}
// Set text color to black
$text_color = imagecolorallocate($image, 0, 0, 0);
// Draw the code text (make sure the font path is correct)
imagettftext($image, 20, 0, 30, 30, $text_color, 'path/to/font.ttf', $code);
// Output the image
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
To show the CAPTCHA image in your form, use a simple HTML tag that references the captcha.php script:
<img src="captcha.php" alt="CAPTCHA">
For better usability, consider adding an option to refresh the CAPTCHA image by clicking on it.
When the user submits the form, you need to compare their input with the code stored in the session. Here's how you can validate the input:
<?php
session_start();
if (isset($_POST['captcha'])) {
$user_input = $_POST['captcha'];
if ($user_input == $_SESSION['captcha_code']) {
// CAPTCHA is correct, proceed with the action
} else {
// CAPTCHA is incorrect, ask user to try again
}
}
?>
This verification logic can be used for login forms, comment forms, or any protected submission scenario.
You’ve now learned how to create a simple CAPTCHA system in PHP using the GD library. This solution generates random codes, adds visual noise to deter bots, and securely stores the code in a session for verification.
To further enhance the CAPTCHA functionality, consider the following improvements:
Use alphanumeric characters instead of just digits
Add interference lines along with random dots
Vary text angle, size, and font
Implement expiration time for the CAPTCHA code
A well-designed CAPTCHA not only improves your site’s security but also provides a smoother user experience.