啥也不說,直接上代碼session
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 }