加乘验证码改进的
下午活少,又刚看php的GD库不久,写个验证码练练手。
没做什么修饰,一路直下,no function,no class!
里边的函数查手册吧,完全不会的先去把php的GD库看一遍。
还是不发首页。
这是效果图:
1 <?php 2 session_start(); 3 /** 4 * 一个简单的加乘验证码类 5 * @author 谭宁宁 6 * @datetime 2012-09-03 7 */ 8 9 class codeimg 10 { 11 public $width = 150; 12 public $height = 35; 13 14 public $num_1 = 1; 15 public $num_2 = 10; 16 17 public $f_file = 'font/msyhbd.ttf'; 18 public $f_size = 13; 19 20 public $c_type = 1; //验证码类型:1加乘混合出现/2纯加法/3纯乘法。默认为1 21 public $imgSourc= ''; 22 23 public $line = true; 24 public $lineNum = 0; 25 26 private $sess = ''; //存入session的值 27 private $dev = FALSE;//调试模式,也就是不输出header("content-type: image/png;");也不生成图片。测试的 28 29 function __construct() 30 { 31 $this->genImg(); 32 } 33 34 function genImg() 35 { 36 $this->imgSourc = $this->createImgSourc(); 37 if(!self::$this->dev) 38 { 39 header("content-type: image/png;"); 40 imagepng($this->imgSourc); 41 imagedestroy($this->imgSourc); 42 } 43 } 44 45 function createImgSourc() 46 { 47 $this->imgSourc = imagecreate($this->width, $this->height); 48 $bgcolor = imagecolorallocate($this->imgSourc, 255, 255, 255); 49 50 //是否生成干扰线 51 if($this->line) 52 { 53 $this->genLine(); 54 } 55 56 $text = $this->genStr(); 57 $strlen = mb_strlen($text); 58 59 $y = intval(($this->height-$this->f_size)); 60 $x = intval(($this->height-$strlen)); 61 62 $textColor = imagecolorallocate($this->imgSourc, rand(0, 125), rand(0, 125), rand(0, 125)); 63 imagettftext($this->imgSourc, $this->f_size, 0, $x, $y, $textColor, $this->f_file, $text); 64 65 return $this->imgSourc; 66 } 67 68 /** 69 * 干扰线线的生成 70 * 根据$this->lineNum决定生成多少条线,默认为随机生成5~12条 71 */ 72 function genLine() 73 { 74 $lineNum = empty($this->lineNum) ? rand(5, 12) : $this->lineNum; 75 for($i = 1; $i <= $lineNum; $i++ ) 76 { 77 $linecolor = imagecolorallocate($this->imgSourc, rand(0 , 255), rand(0, 255), rand(0, 255)); 78 imageline($this->imgSourc, rand(1 , $this->width), rand(1, $this->height), rand(1, $this->width), rand(1, $this->height), $linecolor); 79 } 80 } 81 82 /** 83 * 生成图片里的内容 84 * @return string 85 */ 86 function genStr() 87 { 88 $operArr = array('加', '乘'); 89 $operNum = $this->c_type === 2 ? 0 : ($this->c_type === 3 ? 1 : rand(0, 1)); 90 91 $numArr[0] = rand(intval($this->num_1), intval($this->num_2)); 92 $numArr[1] = rand(intval($this->num_1), intval($this->num_2)); 93 94 if($operNum === 1) 95 { 96 $numArr[2] = intval($numArr[0])*intval($numArr[1]); 97 } 98 else 99 { 100 $numArr[2] = intval($numArr[0])+intval($numArr[1]); 101 } 102 103 $temp_num = rand(0, 2); 104 self::$this->sess = $numArr[$temp_num]; 105 $numArr[$temp_num] = '**'; 106 $string = $numArr[0].' '.$operArr[$operNum].' '.$numArr[1].' = '.$numArr[2]; 107 return $string; 108 } 109 110 function getValue() 111 { 112 return self::$this->sess; 113 } 114 115 } 116 header("content-type: text/html; charset=utf-8"); 117 $objimg = new codeimg(); 118 $_SESSION['scode'] = $objimg->getValue(); 119 ?>