首页  >  文章  >  后端开发  >  一个非常好用的验证码工具类

一个非常好用的验证码工具类

WBOY
WBOY原创
2016-07-25 08:47:391132浏览
  1. /**
  2. * 验证码类
  3. */
  4. class Base_Tool_Verify{
  5. /**
  6. * 生成验证码方法
  7. */
  8. public static function createCode(){
  9. //生成验证码图片
  10. // 全数字
  11. $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"; //要显示的字符,可自己进行增删
  12. $list = explode(",", $str);
  13. $cmax = count($list) - 1;
  14. $verifyCode = '';
  15. for ( $i=0; $i $randnum = mt_rand(0, $cmax);
  16. $verifyCode .= $list[$randnum]; //取出字符,组合成为我们要的验证码字符
  17. }
  18. $_SESSION['code'] = $verifyCode; //将字符放入SESSION中
  19. $im = imagecreate(80,28); //生成图片
  20. $black = imagecolorallocate($im, 0 ,0 ,0); //此条及以下三条为设置的颜色
  21. $white = imagecolorallocate($im, 244,249,244);
  22. $gray = imagecolorallocate($im, rand(200,255),rand(200,255),rand(200,255));
  23. $red = imagecolorallocate($im, rand(200,255), rand(200,255), rand(200,255));
  24. $rand_color = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
  25. $rand_color2 = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
  26. imagefill($im,0,0,$white); //给图片填充颜色
  27. $pix=imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
  28. mt_srand();
  29. for($i=0;$i {
  30. imagesetpixel($im,mt_rand(0,180),mt_rand(0,35),$pix);
  31. }
  32. imageline($im, 0,rand(0,28), 80, rand(0,28), $rand_color);
  33. imageline($im, 0,rand(0,28), 80, rand(0,28), $rand_color2);
  34. //将验证码绘入图片
  35. $mycolor = imagecolorallocate($im, 0, 78, 152);
  36. $path = API_PATH.DS.'Base'.DS.'Tool';
  37. putenv('GDFONTPATH=' . $path);
  38. $font = 'simhei.ttf';
  39. $arrstr = str_split($verifyCode);
  40. imagettftext($im, 20, rand(0,50), 10, rand(20,30), $mycolor, $font, $arrstr[0]);
  41. imagettftext($im, 15, rand(0,50), 20, rand(20,30), $mycolor, $font, $arrstr[1]);
  42. imagettftext($im, 15, rand(0,50), 30, rand(20,30), $mycolor, $font, $arrstr[2]);
  43. imagettftext($im, 15, rand(0,50), 40, rand(20,30), $mycolor, $font, $arrstr[3]);
  44. $font2=imagecolorallocate($im,41,163,238);
  45. imagerectangle($im,0,0,1,1,$font2);
  46. imagepng($im);
  47. imagedestroy($im);
  48. }
  49. }
复制代码


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn