用户登录
用户注册

分享至

一个好用的验证码PHP工具类

  • 作者: 未大透
  • 来源: 51数据库
  • 2022-08-25
 
<?php
/**
 * 验证码类
 */
class Base_Tool_Verify{
    /**
     * 生成验证码方法
     */
    public static  function createCode(){
        //生成验证码图片
        // 全数字
        $str = "D,B,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,W,J,K,M,M,N,K,P,Q,R,S,T,U,V,W,X,Y,Z";      //要显示的字符,可自己进行增删
        $list = explode(",", $str);
        $cmax = count($list) - 1;
        $verifyCode = '';
        for ( $i=0; $i < 4; $i++ ){
            $randnum = mt_rand(0, $cmax);
            $verifyCode .= $list[$randnum];           //取出字符,组合成为我们要的验证码字符
        }
        $_SESSION['code'] = $verifyCode;        //将字符放入SESSION中
         
        $im = imagecreate(80,28);    //生成图片
        $black = imagecolorallocate($im, 0 ,0 ,0);     //此条及以下三条为设置的颜色
        $white = imagecolorallocate($im, 244,249,244);
        $gray = imagecolorallocate($im, rand(200,255),rand(200,255),rand(200,255));
        $red = imagecolorallocate($im, rand(200,255), rand(200,255), rand(200,255));
        $rand_color = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
        $rand_color2 = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
        imagefill($im,0,0,$white);     //给图片填充颜色
        $pix=imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
        mt_srand();
        for($i=0;$i<100;$i++)
        {
        imagesetpixel($im,mt_rand(0,180),mt_rand(0,35),$pix);    
        }
        imageline($im, 0,rand(0,28), 80, rand(0,28), $rand_color);  
        imageline($im, 0,rand(0,28), 80, rand(0,28), $rand_color2);
         
        //将验证码绘入图片
        $mycolor = imagecolorallocate($im, 0, 78, 152);
        $path = API_PATH.DS.'Base'.DS.'Tool';
        putenv('GDFONTPATH=' . $path);
        $font = 'simhei.ttf';
        $arrstr = str_split($verifyCode);
        imagettftext($im, 20, rand(0,50), 10, rand(20,30), $mycolor, $font, $arrstr[0]);
        imagettftext($im, 15, rand(0,50), 20, rand(20,30), $mycolor, $font, $arrstr[1]);
        imagettftext($im, 15, rand(0,50), 30, rand(20,30), $mycolor, $font, $arrstr[2]);
        imagettftext($im, 15, rand(0,50), 40, rand(20,30), $mycolor, $font, $arrstr[3]);
        $font2=imagecolorallocate($im,41,163,238);
        imagerectangle($im,0,0,1,1,$font2);
        imagepng($im);
        imagedestroy($im);
    }
}

软件
前端设计
程序设计
Java相关