With growing concerns about web security, captchas have become a common solution to prevent malicious activities and automated submissions on websites. By implementing captchas, developers can ensure that interactions come from real users. This article walks you through generating a captcha in PHP and integrating it with a form for proper validation.
Captchas usually consist of random characters. The following PHP snippet generates a random captcha string and stores it in a session:
<?php session_start(); // Start the session // Define the length of the captcha $length = 4; // Characters allowed in the captcha $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $code = ''; // Generate the random captcha string for ($i = 0; $i < $length; $i++) { $code .= $str[rand(0, strlen($str) - 1)]; } // Store the lowercase version in session for later validation $_SESSION['code'] = strtolower($code); ?>
Next, we use PHP’s GD library to create an image and embed the captcha string into it:
<?php // Set the width and height of the captcha image $width = 120; $height = 40; // Create a blank canvas $image = imagecreatetruecolor($width, $height); // Define background color $bgColor = imagecolorallocate($image, 255, 255, 255); imagefilledrectangle($image, 0, 0, $width, $height, $bgColor); // Set the text color $textColor = imagecolorallocate($image, 0, 0, 0); // Write the captcha string to the image imagettftext($image, 20, 0, 10, 30, $textColor, 'font.ttf', $code); // Output the image to the browser header('Content-type:image/png'); imagepng($image); // Clean up imagedestroy($image); ?>
This script outputs a PNG image with the random captcha string rendered on it.
To use the captcha in a form, add an input field and display the captcha image:
Users must enter the characters displayed in the image before the form can be submitted.
In your form handler script (`handleForm.php`), compare the entered captcha with the one stored in the session:
<?php session_start(); // Get the user input and convert to lowercase $code = strtolower($_POST['code']); $sessionCode = strtolower($_SESSION['code']); // Compare the values if ($code !== $sessionCode) { echo 'Incorrect captcha'; exit; } // Proceed with handling other form data // ... ?>
If the captcha input is incorrect, an error message is displayed and processing is halted. If correct, the rest of the form logic executes.
This guide demonstrated how to use PHP to generate a captcha string, render it as an image using the GD library, and validate it in a form. Integrating captchas into forms effectively protects websites from spam bots and malicious scripts.
In real-world applications, developers can enhance security further by customizing the character set, adding visual noise or distortions, and adjusting fonts or layout to make the captcha harder for bots to decode while still being readable for humans.