突然有個想法,就是去寫一個簡單的驗證碼類,其實驗證碼在很多框架有自帶的,網上一搜也一大把,我只是想當作是練習,熟悉一下過程。
session_start();class He_Captcha{ private $str = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVW"; private $text; private $im; public $num; public $size; public $width; public $height; public $session_var; public $ttfs = array( 'Jura.ttf', 'AntykwaBold.ttf', 'Duality.ttf', 'VeraSansBold.ttf' ); /* 生成驗證碼 *num 顯示的驗證碼字符數 *size 字符的字體大小 *session_var 驗證碼會話名稱 *width 驗證碼圖片的寬 *height 驗證碼圖片的高 */ public function Captcha($num = 4, $size = 15, $session_var = '', $width = 0, $height = 0){ $this->num = (int)max($this->num, $num); $this->size = (int)max($this->size, $size); $this->width = $width ? (int)max($this->width, $width) : $this->num * $this->size; $this->height = $height ? (int)max($this->height, $height) : $this->size + 10; $this->session_var = strlen(trim($session_var))>2 ? trim($session_var):'captcha'; $this->_getText($this->num); $_SESSION[$this->session_var] = $this->text; $this->im = imagecreatetruecolor($this->width, $this->height);//畫圖像 $this->_drowBackground();//畫背景 $this->_setNoiseLines();//畫干擾線 $this->_setNoisePoints();//畫干擾點 $this->_writeText();//畫驗證碼 $this->_createCaptcha(); } /*創建驗證碼內容*/ private function _getText($num){ for( $i = 0; $i < $num; $i++ ){ $this->text .= $this->str[mt_rand(0,strlen($this->str)-1)]; } } /*畫背景*/ private function _drowBackground(){ $bg_color = imagecolorallocate($this->im, 235, 236, 237); imagefilledrectangle($this->im, 0, 0, $this->width, $this->height, $bg_color); } /*畫干擾點*/ private function _setNoisePoints(){ $points = 2 * $this->width; for($i = 0;$i < $points;$i++){ $font_color = imagecolorallocate($this->im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); imagesetpixel($this->im, mt_rand(0, $this->width), mt_rand(0, $this->height), $font_color); } } /*畫干擾線*/ private function _setNoiseLines(){ $lines = $this->width / 12; for($i = 0; $i < $lines; $i++){ $font_color = imagecolorallocate($this->im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); imagearc($this->im, mt_rand( -$this->width, $this->width), mt_rand( -$this->height, $this->height), mt_rand(30, $this->width * 2), mt_rand(20, $this->height * 2), mt_rand(0, 360), mt_rand(0, 360), $font_color); } } /*畫驗證碼*/ private function _writeText(){ for($i = 0; $i < $this->num; $i++){ $ttf = 'fonts/'.$this->ttfs[array_rand($this->ttfs,1)]; $text_color = imagecolorallocate($this->im, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120)); @imagefttext($this->im, $this->size, mt_rand(-10,10), $this->size*$i, $this->size+5, $text_color, $ttf, $this->text[$i]); } } /*生成驗證碼*/ private function _createCaptcha(){ header("Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate"); header("Content-Type: image/png; charset=utf-8"); imagepng($this->im); imagedestroy($this->im); }}
下面為調用以及生成效果:
$c = new He_Captcha();$c->Captcha();
.........