이미지 기반 CAPTCHA 생성 클래스를 구현하여 웹 폼 보안을 강화할 수 있습니다. GD 라이브러리를 활용한 PHP 구현 예시입니다.
CAPTCHA 클래스 구조
<?php
session_start();
class CaptchaGenerator {
private $charSet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
private $captchaText;
private $textLength = 4;
private $imgWidth = 140;
private $imgHeight = 45;
private $image;
private $fontFile = './arial.ttf';
private $fontSize = 18;
public function __construct() {
// 폰트 경로 설정 필요
}
private function generateText() {
$maxIndex = strlen($this->charSet) - 1;
$this->captchaText = '';
for ($i = 0; $i < $this->textLength; $i++) {
$this->captchaText .= $this->charSet[rand(0, $maxIndex)];
}
}
private function createBackground() {
$this->image = imagecreatetruecolor($this->imgWidth, $this->imgHeight);
$bgColor = imagecolorallocate($this->image, rand(180, 255), rand(180, 255), rand(180, 255));
imagefilledrectangle($this->image, 0, 0, $this->imgWidth, $this->imgHeight, $bgColor);
}
private function drawText() {
$charSpacing = $this->imgWidth / $this->textLength;
for ($i = 0; $i < $this->textLength; $i++) {
$textColor = imagecolorallocate($this->image, rand(0, 120), rand(0, 120), rand(0, 120));
$xPos = $i * $charSpacing + rand(3, 8);
$yPos = $this->imgHeight * 0.7;
imagettftext(
$this->image,
$this->fontSize,
rand(-20, 20),
$xPos,
$yPos,
$textColor,
$this->fontFile,
$this->captchaText[$i]
);
}
}
private function addNoise() {
for ($i = 0; $i < 5; $i++) {
$lineColor = imagecolorallocate($this->image, rand(0, 150), rand(0, 150), rand(0, 150));
imageline(
$this->image,
rand(0, $this->imgWidth),
rand(0, $this->imgHeight),
rand(0, $this->imgWidth),
rand(0, $this->imgHeight),
$lineColor
);
}
for ($j = 0; $j < 70; $j++) {
$pixelColor = imagecolorallocate($this->image, rand(150, 250), rand(150, 250), rand(150, 250));
imagesetpixel(
$this->image,
rand(0, $this->imgWidth),
rand(0, $this->imgHeight),
$pixelColor
);
}
}
private function outputImage() {
header('Content-Type: image/png');
imagepng($this->image);
imagedestroy($this->image);
}
public function render() {
$this->createBackground();
$this->generateText();
$this->drawText();
$this->addNoise();
$this->outputImage();
}
public function getText() {
return strtolower($this->captchaText);
}
}
주의: 실제 사용 시 폰트 파일 경로를 정확히 설정해야 합니다.
CAPTCHA 생성 스크립트
<?php
session_start();
require 'CaptchaGenerator.php';
$generator = new CaptchaGenerator();
$generator->render();
$_SESSION['captcha_code'] = $generator->getText();
HTML에서 사용법
<img src="captcha.php"
alt="CAPTCHA"
onclick="this.src='captcha.php?r='+Math.random()">