PHP如何生成验证码

来源:互联网 发布:神雕侠侣安徽卫视源码 编辑:程序博客网 时间:2024/06/04 13:42

生成验证码的原理很简单,一个字’画’.没错,验证码我们要画的有背景,数字或字母。

效果如图:

步骤如下:
1.获取随机验证码
用getCode函数(自定义),它会返回一个字符串.

2.创建一个图像资源、分配颜色

$m = imagecreatetruecolor($width,$height);

imagecolorallocate,这个其实就是获取一种颜色

3.开始绘画
1).在image图像左上角处开始区域填充背景颜色

imagefill($m,0,0,$bg);

2).添加一个有颜色的矩形框
imagerectangle

3).添加干扰点和干扰线

4).把获取到的验证码字符串画上图像上去

4.输出图像
1).直接输出到浏览器
//注意此函数执行前不能有输出,空格也不行
//如果没有设置响应头,则页面会出现乱码,而不是一张验证码的图像
header(“Content-type:image/png”); //设置响应头信息
imagepng($m);

2).输出到文件中

imagepng($m,'test.png');

5.销毁图像
imagedestroy($m);

代码如下:

/** * @param int $num  验证码的个数,默认为4 * @param int $type 验证码的类型,0:纯数字,1:数字+小写字母 2:数字+大小写字母 * @param bool $outFile 验证码是否输出到文件中 * @return array 以数组形式返回验证码和验证码图片名字 */function drawIdentifyCode($num=4,$type=0,$outFile = true){    //绘制验证码    $code = getCode($num,$type);//获取验证码    $width = $num*35;    $height = 40;//1.创建一个画图像资源、分配颜色    $m = imagecreatetruecolor($width,$height);    $c = array(imagecolorallocate($m,rand(0,255),rand(0,255),rand(0,255)),        imagecolorallocate($m,rand(0,255),rand(0,255),rand(0,255)),        imagecolorallocate($m,rand(0,255),rand(0,255),rand(0,255)),        imagecolorallocate($m,rand(0,255),rand(0,255),rand(0,255)));    $bg = imagecolorallocate($m,220,220,220); //背景颜色//2.开始绘画//在image图像左上角处开始区域填充    imagefill($m,0,0,$bg);//添加一个有颜色的矩形框    imagerectangle($m,0,0,$width-1,39,$c[0]);//添加干扰点    for($i=0;$i<400;$i++)        imagesetpixel($m,rand(0,$width),rand(0,30),$c[$i%4]);//添加干扰线    for($i=0;$i<5;$i++)        imageline($m,rand(0,$width),rand(0,30),rand(0,$width),rand(0,30),$c[$i%4]);//绘制验证码内容(一个一个字符绘制)    for($i=0;$i<$num;$i++)        imagettftext($m,28,rand(-50,50),15+(28*$i),30,$c[$i%4],"consola.ttf",$code[$i]);//3.输出图像    $fileName = null;    if(!$outFile)    {        //注意此函数执行前不能有输出,空格也不行        //如果没有设置响应头,则页面会出现乱码,而不是一张验证码的图像        header("Content-type:image/png"); //设置响应头信息        imagepng($m);    }    else    {        $fileName = time().'.png';        imagepng($m,$fileName);    }//4.销毁图片    imagedestroy($m);    return array($code,$fileName);}/** * @function 随机生成一个验证码的函数 * @param $m: 验证码的个数(默认为4) * @param $type:验证码的类型:0:纯数字,1:数字+小写字母 2:数字+大小写字母 * @return 返回字符串形式的验证码  */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;}
0 0
原创粉丝点击