mCheckCode = $this->mKey( $this->mCheckCodeNum, 'ALNUM' ); return $this->mCheckCode; } private function mKey($len = 4, $type = 'ALNUM') { // Register the lower case alphabet array $alpha = array( 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ); // Register the upper case alphabet array $ALPHA = array( 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ); // Register the numeric array $num = array( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ); // Initialize the keyVals array for use in the for loop $keyVals = array(); // Initialize the key array to register each char $key = array(); // Loop through the choices and register // The choice to keyVals array switch($type) { case 'lower' : $keyVals = $alpha; break; case 'upper' : $keyVals = $ALPHA; break; case 'numeric' : $keyVals = $num; break; case 'ALPHA' : $keyVals = array_merge( $alpha, $ALPHA ); break; case 'ALNUM' : $keyVals = array_merge( $ALPHA, $num ); break; } // Loop as many times as specified // Register each value to the key array for($i = 0; $i <= $len - 1; $i ++) { $r = rand( 0, count( $keyVals ) - 1 ); $key [$i] = $keyVals [$r]; } // Glue the key array into a string and return it return join( "", $key ); } /** * @brief 产生验证码图片 */ private function CreateImage() { $this->mCheckImage = @imagecreate( $this->mCheckImageWidth, $this->mCheckImageHeight ); imagecolorallocate( $this->mCheckImage, 200, 200, 200 ); return $this->mCheckImage; } /** * @brief 设置图片的干扰像素 */ private function SetDisturbColor() { for($i = 0; $i <= 128; $i ++) { $this->mDisturbColor = imagecolorallocate( $this->mCheckImage, rand( 0, 255 ), rand( 0, 255 ), rand( 0, 255 ) ); imagesetpixel( $this->mCheckImage, rand( 2, 128 ), rand( 2, 38 ), $this->mDisturbColor ); } } /** * * * @brief 设置验证码图片的大小 * * @param $width 宽 * * @param $height 高 * */ public function SetCheckImageWH($width, $height) { if($width == '' || $height == '') return false; $this->mCheckImageWidth = $width; $this->mCheckImageHeight = $height; return true; } /** * @brief 在验证码图片上逐个画上验证码 */ private function WriteCheckCodeToImage() { for($i = 0; $i <= $this->mCheckCodeNum; $i ++) { $bg_color = imagecolorallocate( $this->mCheckImage, rand( 0, 255 ), rand( 0, 128 ), rand( 0, 255 ) ); $x = floor( $this->mCheckImageWidth / $this->mCheckCodeNum ) * $i; $y = rand( 0, $this->mCheckImageHeight - 15 ); imagechar( $this->mCheckImage, 5, $x, $y, $this->mCheckCode [$i], $bg_color ); } } /** * @brief 输出验证码图片 */ public function OutCheckImage() { $this->OutFileHeader(); $this->CreateImage(); $this->SetDisturbColor(); $this->WriteCheckCodeToImage(); imagepng( $this->mCheckImage ); imagedestroy( $this->mCheckImage ); } }