Captcha class Validatecode {private $charset = ' abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789 ';//random factor private $ code;//Verification Code Private $codelen = 4;//captcha length Private $width = 130;//width Private $height = 50;//height private $img;//graphics resource handle private $font;//The specified font private $fontsize = 20;//Specifies the font size of private $fontcolor;//Specifies the font color//constructor method to initialize public function __construct () {$this ->font = DirName (__file__). ' /font/elephant.ttf ';//Note the font path to write to, otherwise not show the picture}//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 line, snowflake Private Function Createline () {//Line 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); }//Snowflake for ($i =0; $i <100; $i + +) {$color = Imagecolorallocate ($this->img,mt_rand (200,255), Mt_rand (200,255), Mt_ran D (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 doimg () {$this->createbg (); $this->createcode (); $this->createline (); $this->createfont (); $this->output (); }//Get Verification Code Public Function GetCode () {return strtolower ($this->code);}}
How to use:
1, first save the verification code class as a file named ValidateCode.class.php;
2. Create a new file named captcha.php to call the class;
captcha.php
3, refer to the page, the code is as follows:
4, a complete verification page, the code is as follows:
<?phpsession_start (); On the page first to open session,//error_reporting (2047); Session_destroy (); Remove the session to get a new session value each time; With seesion effect is good, also very convenient? >