生成验证码代码如下:
public function captcha(){//初始化$border = 1;$how = 4;$w = 117;$h = 42;$y = 29;$fontsize = 18;$alpha = \"abcdefghjkmnpqrstuvwxyz\";$number = \"23456789\";$captchacode = \"\";srand((double)microtime()*1000000);$font = VAR_PATH . \"font/arialbd.ttf\";$img = imagecreate($w, $h);//绘制基本框架$bgcolor = imagecolorallocate($img, 247, 255, 236);imagefill($img, 0, 0, $bgcolor);if ($border) {$black = imagecolorallocate($img, 204, 204, 204);imagerectangle($img, 0, 0, $w-1, $h-1, $black);}//逐位产生随机字符$j = 0;for ($i = 0; $i < $how; $i++) {$alpha_or_number = mt_rand(0, 1);$str = $alpha_or_number ? $alpha : $number;$which = mt_rand(0, strlen($str)-1);$code = substr($str, $which, 1);$j = !$i ? 15 : $j+25;$color3 = imagecolorallocate($img, 87, 123, 35);imagettftext($img, $fontsize, 0, $j, $y, $color3, $font, $code);//imagechar($img, $fontsize, $j, $y, $code, $color3);$captchacode .= $code;}//绘背景干扰线/*for ($i=0; $i<10; $i++) {$color1 = imagecolorallocate($img, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));imagearc($img, mt_rand(-5,$w), mt_rand(-5,$h), mt_rand(20,300), mt_rand(20,200), 55, 44, $color1);}*/$_SESSION[\'captchacode\'] = $captchacode;header(\"Content-type: image/gif\");imagegif ($img);imagedestroy($img);exit;}
验证码显示html区域
<div class=\"field\"><label>验证码</label><div class=\"input-box\"><input type=\"text\" class=\"input-text required\" name=\"captcha\" style=\"width:197px;\" /><img src=\"<?php echo $this->getUrl(\'index/index/captcha\'); ?>\" οnclick=\"this.src=this.src+\'?\';\" title=\"点击刷新验证码\" style=\"cursor:pointer;\" /></div></div>