<?php
class ImageCode {
private $width; // 驗證碼圖片寬度
private $height; // 驗證碼圖片高度
private $codeNum; // 驗證碼字元個數
private $checkCode; // 驗證碼字串
private $image; // 圖片資源
public function __construct($width=60, $height=20, $codeNum=4) {
$this->width = $width;
$this->height = $height;
$this->codeNum = $codeNum;
$this->checkCode = $this->createCheckCode();
}
public function getCreateImage() {
$this->createImage();
$this->outputText();
$this->setDisturbColor();
$this->outputImage();
}
public function getCheckCode() {
return $this->checkCode;
}
private function createImage() {
$this->image = imagecreatetruecolor($this->width, $this->height);
$bg = imagecolorallocate($this->image, 255, 255, 255); // 白底
$border = imagecolorallocate($this->image, 0, 0, 0); // 黑框
imagefilledrectangle($this->image, 0, 0, $this->width-1, $this->height-1, $bg);
imagerectangle($this->image, 0, 0, $this->width-1, $this->height-1, $border);
}
private function createCheckCode() {
$code = '';
for ($i=0; $i < $this->codeNum; $i++) {
$type = rand(0, 2);
switch ($type) {
case 0: $char = chr(rand(48, 57)); break; // 0-9
case 1: $char = chr(rand(65, 90)); break; // A-Z
case 2: $char = chr(rand(97, 122)); break; // a-z
}
$code .= $char;
}
return $code;
}
private function outputText() {
for ($i=0; $i < $this->codeNum; $i++) {
$x = ($i+1) * (($this->width-10) / $this->codeNum);
$y = rand(2, $this->height-4);
$color = imagecolorallocate($this->image, rand(0,150), rand(0,150), rand(0,150));
imagechar($this->image, 5, $x, $y, $this->checkCode[$i], $color);
}
}
private function setDisturbColor() {
for ($i=0; $i <= 100; $i++) {
$color = imagecolorallocate($this->image, rand(0,255), rand(0,255), rand(0,255));
imagesetpixel($this->image, rand(1,$this->width-2), rand(1,$this->height-2), $color);
}
}
private function outputImage() {
header('Content-Type: image/png');
imagepng($this->image);
}
public function __destruct() {
imagedestroy($this->image);
}
}
?>
<?php
session_start();
$captcha = new ImageCode(80, 30, 5);
$_SESSION['captcha_code'] = $captcha->getCheckCode();
$captcha->getCreateImage();
?>
驗證時比對 $_SESSION['captcha_code'] 與用戶輸入(建議轉大小寫不敏感比對)。
imagettftext)提升視覺效果