Implementing a Simple CAPTCHA Generator and Recognizer in PHP
This article demonstrates how to create a basic CAPTCHA image with PHP, convert it to a binary matrix, segment characters, extract feature patterns, and recognize the code by matching against stored templates, providing full source code and a sample execution result.
The article explains why many web pages use CAPTCHAs and questions their security, then shows a simple PHP program that both generates and cracks such CAPTCHAs.
CAPTCHA Generation – A 4‑character code is randomly built from alphanumeric characters, drawn onto a 60×30 image with random background colors, and output as PNG data.
Binary Conversion (Binarization) – The generated image is read pixel by pixel; black pixels are marked with "*" and others with "0" to create a binary matrix.
Segmentation – Columns containing only zeros are filtered out, the remaining columns are grouped into character blocks, and empty rows are removed to isolate each character.
Feature Extraction – For each isolated character, a string representation is built and compared with a predefined set of feature patterns for letters, digits and symbols.
Recognition – The similarity between the extracted pattern and each stored pattern is calculated using similar_text; the character with the highest similarity is selected as the recognized symbol.
PHP Implementation
/**
* Simple CAPTCHA recognizer
* @author zhjx922
*/
class vCode {
// character feature patterns
private $_wordKeys = array(
'A' => '000**00000****000**00**0**0000****0000****0000************0000****0000****0000**',
// ... (other patterns omitted for brevity) ...
'9' => '00****000**00**0**0000****0000**0**00***00***0**000000**0*0000**0**00**000****00'
);
/**
* Generate CAPTCHA image
* @author 武老师
*/
public function make($verCode = '') {
if (empty($verCode)) {
$baseChars = 'ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789';
$verCode = '';
$codeCharLenth = 4;
for ($i = 1; $i <= $codeCharLenth; $i++) {
$verCode .= $baseChars{mt_rand(0, strlen($baseChars) - 1)};
}
}
$font_size = 20;
$width = 60;
$height = 30;
$img = imagecreate($width, $height);
$bgR = mt_rand(50, 200);
$bgG = mt_rand(50, 200);
$bgB = mt_rand(50, 200);
$background = imagecolorallocate($img, $bgR, $bgG, $bgB);
$black = imagecolorallocate($img, 0, 0, 0);
imagestring($img, 5, 9, 8, $verCode, $black);
ob_start();
imagepng($img);
$image = ob_get_contents();
ob_end_clean();
return array('image' => $image, 'code' => $verCode);
}
/**
* Convert image string to binary matrix
*/
public function getImage($imageString) {
$im = imagecreatefromstring($imageString);
list($width, $height) = getimagesizefromstring($imageString);
$image = array();
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$rgb = imagecolorat($im, $x, $y);
$rgb = imagecolorsforindex($im, $rgb);
$image[$y][$x] = ($rgb['red'] == 0 && $rgb['green'] == 0 && $rgb['blue'] == 0) ? '*' : 0;
}
}
return $image;
}
// ... (methods remove, removeByLine, getWordString, match, show omitted for brevity) ...
}
$vCode = new vCode();
$codeImage = $vCode->make();
$imageString = $codeImage['image'];
$image = $vCode->getImage($imageString);
$vCode->show($image);
$newImage = $vCode->remove($image);
$code = '';
foreach ($newImage as $img) {
$vCode->show($img);
$code .= $vCode->match($img)['key'];
}
echo "生成的验证码为:{$codeImage['code']}
";
echo "识别的验证码为:{$code}
";The script prints the original binary image, the segmented characters, and finally displays both the generated CAPTCHA code and the code recognized by the algorithm, demonstrating that a simple pattern‑matching approach can successfully break the example CAPTCHA.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
