生成验证码
啥也不说,直接上代码
1 class Captcha 2 { 3 4 /** 5 * 生成验证码 6 * 7 * @param int $length 码字符长度 8 * @param int $width 宽度 9 * @param int $height 长度 10 * @param string $type 类型 11 * @return string 12 */ 13 public static function createCode($length = 4, $width = 45, $height = 30, $type = 'png') 14 { 15 session_start(); 16 $code = self::randCode($length); 17 $_SESSION['captcha'] = $code; 18 $img = @imagecreatetruecolor($width, $height); //新建一个真彩色图像 19 //画一矩形并填充 20 $color = imagecolorallocate($img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255)); 21 @imagefilledrectangle($img, 0, 0, $width, $height, $color); 22 //干扰线 23 for ($i = 0; $i < 3; $i++) { 24 $color = imagecolorallocate($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); 25 @imageline($img, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $color); 26 } 27 //画验证码 28 $codeColor = imagecolorallocate($img, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120)); 29 @imagestring($img, 5, 5, 8, $code, $codeColor); 30 //生成图像 31 header("Content-type: Image/" . $type); 32 $ImageFun = 'Image' . $type; 33 $ImageFun($img); 34 imagedestroy($img); 35 } 36 37 /** 38 * 生成随机验证码 39 * 40 * @param int $length 生成长度 41 * @return string 42 */ 43 public static function randCode($length) 44 { 45 $string = "0123456789abcdefghijklmnopqrstuvwxyz"; 46 $code = ''; 47 for ($i = 0; $i < $length; $i++) { 48 $code .= $string[mt_rand(0, strlen($string) - 1)]; 49 } 50 return $code; 51 } 52 }