首頁  >  文章  >  後端開發  >  一個非常好用的驗證碼工具類

一個非常好用的驗證碼工具類

WBOY
WBOY原創
2016-07-25 08:47:391114瀏覽
  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 < 4; $i ){
  16. $randnum = mt_rand(0, $cmax);
  17. $verifyCode .= $list[$randnum]; //取出字符,组合成为我们要的验证码字符
  18. }
  19. $_SESSION['code'] = $verifyCode; //将字符放入SESSION中
  20. $im = imagecreate(80,28); //生成图片
  21. $black = imagecolorallocate($im, 0 ,0 ,0); //此条及以下三条为设置的颜色
  22. $white = imagecolorallocate($im, 244,249,244);
  23. $gray = imagecolorallocate($im, rand(200,255),rand(200,255),rand(200,255));
  24. $red = imagecolorallocate($im, rand(200,255), rand(200,255), rand(200,255));
  25. $rand_color = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
  26. $rand_color2 = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
  27. imagefill($im,0,0,$white); //给图片填充颜色
  28. $pix=imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
  29. mt_srand();
  30. for($i=0;$i<100;$i )
  31. {
  32. imagesetpixel($im,mt_rand(0,180),mt_rand(0,35),$pix);
  33. }
  34. imageline($im, 0,rand(0,28), 80, rand(0,28), $rand_color);
  35. imageline($im, 0,rand(0,28), 80, rand(0,28), $rand_color2);
  36. //将验证码绘入图片
  37. $mycolor = imagecolorallocate($im, 0, 78, 152);
  38. $path = API_PATH.DS.'Base'.DS.'Tool';
  39. putenv('GDFONTPATH=' . $path);
  40. $font = 'simhei.ttf';
  41. $arrstr = str_split($verifyCode);
  42. imagettftext($im, 20, rand(0,50), 10, rand(20,30), $mycolor, $font, $arrstr[0]);
  43. imagettftext($im, 15, rand(0,50), 20, rand(20,30), $mycolor, $font, $arrstr[1]);
  44. imagettftext($im, 15, rand(0,50), 30, rand(20,30), $mycolor, $font, $arrstr[2]);
  45. imagettftext($im, 15, rand(0,50), 40, rand(20,30), $mycolor, $font, $arrstr[3]);
  46. $font2=imagecolorallocate($im,41,163,238);
  47. imagerectangle($im,0,0,1,1,$font2);
  48. imagepng($im);
  49. imagedestroy($im);
  50. }
  51. }
复制代码


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn