php生成验证码,是使用gd库生成

整体流程

  1. 创建背景图像

  2. 写入验证码

  3. 加入干扰像素

  4. 输出图像

<?php
session_start();//启动Session
$info = imagecreatetruecolor(80,30);//新建真色彩图像
$background = imagecolorallocate($info,255,255,255);//设置图像背景颜色
imagefill($info,0,0,$background);//给图像背景填充颜色
$rand=null;
$font='./data/font/font.ttf'; //自定义字体
$x=0;               //水平位置
$val=array(0,1,2,3,4,5,6,7,8,9,0, 'q','w','e','r','t','y','u','i','o','p',
           'a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m');
$vcode='';
if(file_exists($font)&&function_exists('imagettftext')){
    for($i=0;$i<4;$i++){
        $rand=$val[rand(0,count($val)-1)];
        $vcode.=$rand;
        if(rand(0,1)){
            $rand=strtoupper($rand);
        }
        $textcolor = imagecolorallocate($info,mt_rand(0,200),
            mt_rand(0,200),mt_rand(0,200)); //设置字体颜色
        imagettftext($info, 18, rand(-30,30), rand($x,$x+5) ,
            rand(20,25), $textcolor, $font, $rand);
        $x+=20;
    }
}else{
    for($i=0;$i<4;$i++){
        $rand=$val[rand(0,count($val)-1)];
        $vcode.=$rand;
        if(rand(0,1)){
            $rand=strtoupper($rand);
        }
        $textcolor = imagecolorallocate($info,mt_rand(0,200),
            mt_rand(0,200),mt_rand(0,200)); //设置字体颜色
        imagestring($info, 5 , rand($x,$x+10), rand(0,15), 
            $rand, $textcolor);////给图像水平写入字符 
        $x+=20;
    }
}
//加入干扰像素
for($i=0;$i<200;$i++){ 
    $randcolor = ImageColorallocate($info,rand(0,255),
        rand(0,255),rand(0,255)); 
    imagesetpixel($info, rand(0,80), rand(0,30) , $randcolor); 
}
$_SESSION['v_code1']=$vcode;
header("content-type:image/jpeg");//声明输出内容格式
imagepng($info);//输入图像
imagedestroy($info);//释放内存
Scroll to Top