首页 > 编程 > PHP > 正文

PHP之验证码生成和使用

2019-11-14 10:33:43
字体:
来源:转载
供稿:网友
 一、通过做一个验证码,掌握GD库绘图原理及常用函数  二、涉及函数知识:     1. GD库函数:imagecreatetruecolor ( int x_size, int y_size ) //创建一个基于真彩的画布imagecolorallocate ( resource image, int red, int green, int blue )//分配一个颜色imagefill ( resource image, int x, int y, int color )//区域填充imagerectangle ( resource image, int x1, int y1, int x2, int y2, int col )//矩形框imagesetpixel ( resource image, int x, int y, int color ) //画一个像素点:imageline ( resource image, int x1, int y1, int x2, int y2, int color )//画一条线段//绘制文本内容imagettftext ( resource image, float size, float angle, int x, int y, int color, string fontfile, string text )imagepng ( resource image [, string filename] )//以 PNG 格式将图像输出到浏览器或文件imagedestroy ( resource image ) //销毁一个图像      2. 其他函数:int rand ( [int min, int max] ) //产生一个随机整数strlen()//获取字串长度的函数header()//设置响应头信息。三、绘图过程1. 创建一个画布、分配颜色imagecreatetruecolor()imagecolorallocate()2. 开始绘画3. 输出图像imagepng()imagejpeg()...4. 销毁图片(释放内容)imagedestroy();四、绘制验证码的具体实现步骤:1. 复制一个字体文件。2. 定义一个函数:随机生成一个验证码的内容3. 开始绘画验证码(加干扰点,干扰线。。。)4. 输出验证码五、验证的使用    在html的代码中使用<img/>标签,使用src属性直接指定图片的url地址即可<img src="code.php" onclick="this.src='code.php?id='+Math.random()"/><?php//绘制验证码(生成)$num=4; //验证码的长度$str = getCode($num,0);// 使用下面的自定义函数,获取需要的验证码值//1. 创建一个画布、分配颜色$width=$num*20;//宽度$height=30;//高度$im = imagecreatetruecolor($width,$height);//创建一个画布//定义几个颜色(输出不同颜色的验证码)$color[] = imagecolorallocate($im,111,0,55);$color[] = imagecolorallocate($im,0,77,0);$color[] = imagecolorallocate($im,0,0,160);$color[] = imagecolorallocate($im,221,111,0);$color[] = imagecolorallocate($im,220,0,0);$bg = imagecolorallocate($im,240,240,240);//背景//2. 开始绘画 imagefill($im,0,0,$bg); imagerectangle($im,0,0,$width-1,$height-1,$color[rand(0,4)]); //随机添加干扰点 for($i=0;$i<200;$i++){ $c = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));//随机一个颜色 imagesetpixel($im,rand(0,$width),rand(0,$height),$c); } //随机添加干扰线 for($i=0;$i<5;$i++){ $c = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));//随机一个颜色 imageline($im,rand(0,$width),rand(0,$height),rand(0,$width),rand(0,$height),$c); } //绘制验证码内容(一个一个字符绘制): for($i=0;$i<$num;$i++){ imagettftext($im,18,rand(-40,40),8+(18*$i),24,$color[rand(0,4)],"msyh.ttf",$str[$i]); }//3. 输出图像header("Content-Type:image/png");//设置响应头信息(注意此函数实行前不可以有输出)imagepng($im);//4. 销毁图片(释放内容)imagedestroy($im);/** * 随机生成一个验证码的内容的函数 * @param $m :验证码的个数(默认为4) * @param $type : 验证码的类型:0:纯数字 1:数字+小写字母 2:数字+大小写字符 */function getCode($m=4,$type=0){ $str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; $t = array(9,35,strlen($str)-1); //随机生成验证码所需内容 $c=""; for($i=0;$i<$m;$i++){ $c.=$str[rand(0,$t[$type])]; } return $c;}//echo getCode();?>注意:需要msyh.ttf字体
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表