Class captcha{
Private $charset = ' abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789 '; Random factor,
Private $code; Verification Code String
Private $codelen = 4; Verification Code length
Private $width = 150; Width
Private $height = 40; Height
Private $img; Graphics resource Handle
Private $font; The specified font
Private $fontsize = 20; Specify font size
Private $fontcolor; Specify font Color
Constructor method Initialization
Public function __construct ($codelen =4, $width =150, $height =40, $fontsize = A, $font = "Elephant.ttf") {
$this->codelen = $codelen;
$this->width = $width;
$this->height = $height;
$this->fontsize = $fontsize;
$this->font = $font;
}
Generate Random Code
Private Function Createcode () {
$_len = strlen ($this->charset)-1;
for ($i =0; $i < $this->codelen; $i +) {
$this->code. = $this->charset[mt_rand (0,$_len)];
}
}
Generate background
Private Function Createbg () {
$this->img = Imagecreatetruecolor ($this->width, $this->height);
$color = Imagecolorallocate ($this->img, Mt_rand (157,255), Mt_rand (157,255), Mt_rand (157,255));
Imagefilledrectangle ($this->img,0, $this->height, $this->width,0, $color);
}
Generate text
Private Function CreateFont () {
$_x = $this->width/$this->codelen;
for ($i =0; $i < $this->codelen; $i +) {
$this->fontcolor = imagecolorallocate ($this->img,mt_rand (0,156), Mt_rand (0,156), Mt_rand (0,156));
Imagettftext ($this->img, $this->fontsize,mt_rand ( -30,30), $_x* $i +mt_rand (1,5), $this->height/1.4, $this- >fontcolor, $this->font, $this->code[$i]);
}
}
Generate lines, snowflakes
Private Function Createline () {
for ($i =0; $i <6; $i + +) {
$color = Imagecolorallocate ($this->img,mt_rand (0,156), Mt_rand (0,156), Mt_rand (0,156));
Imageline ($this->img,mt_rand (0, $this->width), Mt_rand (0, $this->height), Mt_rand (0, $this->width), Mt_ Rand (0, $this->height), $color);
}
for ($i =0; $i <100; $i + +) {
$color = Imagecolorallocate ($this->img,mt_rand (200,255), Mt_rand (200,255), Mt_rand (200,255));
Imagestring ($this->img,mt_rand (1,5), Mt_rand (0, $this->width), Mt_rand (0, $this->height), ' * ', $color);
}
}
Output
Private Function OutPut () {
Header (' content-type:image/png ');
Imagepng ($this->img);
Imagedestroy ($this->img);
}
External generation
Public Function Generatecode () {
$this->CREATEBG ();
$this->createcode ();
$this->createline ();
$this->createfont ();
$this->output ();
}
Get Verification Code
Public Function GetCode () {
Return Strtolower ($this->code);
}
}
Invoke instance
$c = new Captcha ();
$c->generatecode ();
$_session[' captcha '] = $c->getcode ();
Verification code class, generate verification code