In web Captcha is the Technique using which we can protect spam users. Today hackers are very cleaver. Let’s talk about a login page. Here someone can easily enter spam records using a script. Captcha gives confirmation that the user is a real-human. The story behind Captcha is “We generate a random string and store that in server. In the next moment showing the same string to the user as an image. To validate comparing server session value with user input against the image”. In below demo app I am creating a PHP Captcha.
Understanding CAPTCHA
CAPTCHAs serve as a barrier against automated attacks, such as brute-force login attempts, spam form submissions, and credential stuffing. By presenting a challenge that requires human-like interpretation—such as distorted text, image recognition, or logical puzzles—CAPTCHAs help protect web applications from abuse.
String-to-image CAPTCHAs are particularly effective because they rely on visual distortion, noise, and variable fonts to prevent optical character recognition (OCR) tools from extracting the text.
How String-to-Image CAPTCHA Works?
1. String Generation: A random string (usually alphanumeric) is generated.
2. Image Creation: The string is rendered onto an image with distortions, such as warping, overlapping lines, or varying colors.
3. Session Storage: The CAPTCHA value is stored server-side (e.g., in a session) for later validation.
4. User Input: The user reads the image and submits the text via a form.
5. Validation: The submitted text is compared against the stored value.
Here I defined 4 functions CAPTCHA, randomString, hexadecimalToRGB and alignImageToCenter. The function CAPTCHA is responsible to Create Captcha image. It accepts 4 params $textColor, $backgroundColor, $imgWidth, $imgHeight. $textColor is the color for text. $backgroundColor is the captcha background. $imgWidth & $imgHeight is decides area for capatch. randomString function generating random strings which I am converting later into Captcha image. hexadecimalToRGB is the color converter function. While generating image alignImageToCenter is responsible for aling random string to center.
The base function to generate Captcha is “CAPTCHA”. In this function initially I am with some configurable variables. Then generating a random string and providing style. Finally using PHP imagettftext() function generating the Captcha image.
PHP-Captcha.php
<?php /*Executing the Function Captcha*/ CAPTCHA('#162453', '#fff', 120, 40); /*Function to Generate Captcha*/ function CAPTCHA($textColor, $backgroundColor, $imgWidth, $imgHeight) { /* Configuration Settings */ $font = './font/mono.ttf'; $fontSize = $imgHeight * 0.75; $textColor = hexadecimalToRGB($textColor); /*Generating and Storing random string to $rnd variable*/ $rnd = randomString(); $im = imagecreatetruecolor($imgWidth, $imgHeight); $textColor = imagecolorallocate($im, $textColor['r'], $textColor['g'], $textColor['b']); $bgColor = hexadecimalToRGB($backgroundColor); $backgroundColor = imagecolorallocate($im, $bgColor['r'],$bgColor['g'],$bgColor['b']); imagefill($im, 0, 0, $backgroundColor); list($x, $y) = alignImageToCenter($im, $rnd, $font, $fontSize); imagettftext($im, $fontSize, 0, $x, $y, $textColor, $font, $rnd); /*Displaying image*/ imagejpeg($im, NULL, 90); /*Declaring Image Type*/ header('Content-Type: image/jpeg'); imagedestroy($im);/* Destroying image instance */ /*Storing the random string to a Session variable*/ if(isset($_SESSION)){ $_SESSION['captcha_code'] = $rnd;/* set random text in session for captcha validation*/ } } /*This for is responsible to generate Random string for Captcha*/ function randomString($length=6){ $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } /*Using this function I am extracting RBG value form Hexadecimal Color*/ function hexadecimalToRGB($colour) { $hex = str_replace("#", "", $colour); if(strlen($hex) == 3) { $red = hexdec(substr($hex,0,1).substr($hex,0,1)); $green = hexdec(substr($hex,1,1).substr($hex,1,1)); $blue = hexdec(substr($hex,2,1).substr($hex,2,1)); } else { $red = hexdec(substr($hex,0,2)); $green = hexdec(substr($hex,2,2)); $blue = hexdec(substr($hex,4,2)); } return array( 'r' => $red, 'g' => $green, 'b' => $blue ); } /*Function to position Image to the Center*/ function alignImageToCenter($image, $text, $font, $size, $angle = 8) { $xi = imagesx($image); $yi = imagesy($image); $box = imagettfbbox($size, $angle, $font, $text); $xr = abs(max($box[2], $box[4])); $yr = abs(max($box[5], $box[7])); $x = intval(($xi - $xr) / 2); $y = intval(($yi + $yr) / 2); return array($x, $y); } ?>
To run the above code additionally you required to Create a font folder in root directory. Download a ttf image file. Put that in the font folder. Without ttf font file this PHP Captcha program will not run.
Enhancing CAPTCHA Security
1. Dynamic Distortion: Vary the distortion level for each character.
2. Variable Length: Randomize the string length.
3. Case Sensitivity: Enforce case sensitivity if needed.
4. Expiration: Set a time limit for CAPTCHA validity.
5. Rate Limiting: Limit CAPTCHA attempts per IP.
Alternatives to Traditional CAPTCHA
While string-to-image CAPTCHAs are effective, they can be inconvenient for users. Alternatives include:
– reCAPTCHA (Google): Uses behavioral analysis and image recognition.
– hCaptcha: Privacy-focused alternative to reCAPTCHA.
– Math-Based CAPTCHA: Requires solving a simple arithmetic problem.
Conclusion
String-to-image CAPTCHA remains a reliable method for preventing automated attacks while maintaining accessibility for human users. By leveraging PHP’s GD library, developers can implement a customizable CAPTCHA system with varying levels of complexity. However, balancing security and usability is crucial—excessive distortion may frustrate users, while insufficient measures may fail to deter bots. For high-security applications, integrating third-party solutions like reCAPTCHA may offer better protection with minimal development overhead.