您的位置:首页 > 编程语言 > PHP开发

PHP实现自己的验证码(实例)

2016-06-28 11:59 597 查看
想不想自己制作一个漂亮的验证码呢?其实利用PHP的GD库制作一个验证码还是很容易的,只要理清楚思路就好了。

<?php
session_start();
/*
*$width:验证码宽 $height:验证码高 $codenum:验证码字体个数 $codesize:验证码字体大小 $points:干扰点个数 $lines:干扰线条数
*注:使用前应该开启session_start();
*/

function captcha($width,$height,$codenum,$codesize,$points,$lines){
$image = imagecreatetruecolor($width,$height);//设置验证码图片大小函数
//设置验证码颜色 imagecolorallocate(int image, int red, int green, int blue);
$bgcolor = imagecolorallocate($image,255,255,255);
//区域填充 int imagefill(int image, int x, int y, int col)  (x,y) 所在的区域着色,col 表示欲涂上的颜色
imagefill($image,0,0,$bgcolor);
//设置变量
$captch_code = '';
//生成随机数字
for($i=0;$i<$codenum;$i++){
$fontsize = $codesize;//字体大小
//设置字体颜色,随机颜色
$fontcolor = imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));
$checkdate = 'abcdefghijkmnprstuvwxy345678';
//设置验证码内容
$fontcontent = substr($checkdate,rand(0,strlen($checkdate)),1);

//设置坐标
$x = ($i*$width)/$codenum+rand(5,10);
$y = rand(5,10);

imagestring($image,20,$x,$y,$fontcontent,$fontcolor);
}
//存到SESSION
$_SESSION['authcode'] = $captch_code;
//增加干扰元素(干扰点)
for($i=0;$i<$points;$i++){
$pointcolor = imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));
imagesetpixel($image,rand(1,$width-1),rand(1,$height-1),$pointcolor);
}
//增加干扰元素(干扰线)
for($i=0;$i<$lines;$i++){
$linecolor=imagecolorallocate($image,rand(80,220),rand(80,220),rand(80,220));
imageline($image,rand(1,$width-1),rand(1,$height-1),rand(1,$width-1),rand(1,$height-1),$linecolor);
}

header('content-type:image/png');
//建立png图形函数
imagepng($image);

//结束图形函数,销毁$image
imagedestroy($image);
}
captcha(100,30,4,20,300,4);
?>


运行结果:

注:因为图片放大过,所以看上去有点模糊

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php session 验证码 实例