一个好用的自定义验证码生成函数

来源:互联网 发布:优化ping到淘宝时间 编辑:程序博客网 时间:2024/05/16 12:26
  1. getCode(4,60,20);  
  2.   
  3. function getCode($num,$w,$h) {  
  4.     $code = "";  
  5.     for ($i = 0; $i < $num; $i++) {  
  6.         $code .= rand(0, 9);  
  7.     }  
  8.     //4位验证码也可以用rand(1000,9999)直接生成  
  9.     //将生成的验证码写入session,备验证时用  
  10.     $_SESSION["helloweba_num"] = $code;  
  11.     //创建图片,定义颜色值  
  12.     header("Content-type: image/PNG");  
  13.     $im = imagecreate($w, $h);  
  14.     $black = imagecolorallocate($im, 0, 0, 0);  
  15.     $gray = imagecolorallocate($im, 200, 200, 200);  
  16.     $bgcolor = imagecolorallocate($im, 255, 255, 255);  
  17.     //填充背景  
  18.     imagefill($im, 0, 0, $gray);  
  19.   
  20.     //画边框  
  21.     imagerectangle($im, 0, 0, $w-1, $h-1, $black);  
  22.   
  23.     //随机绘制两条虚线,起干扰作用  
  24.     $style = array ($black,$black,$black,$black,$black,  
  25.         $gray,$gray,$gray,$gray,$gray  
  26.     );  
  27.     imagesetstyle($im, $style);  
  28.     $y1 = rand(0, $h);  
  29.     $y2 = rand(0, $h);  
  30.     $y3 = rand(0, $h);  
  31.     $y4 = rand(0, $h);  
  32.     imageline($im, 0, $y1, $w, $y3, IMG_COLOR_STYLED);  
  33.     imageline($im, 0, $y2, $w, $y4, IMG_COLOR_STYLED);  
  34.   
  35.     //在画布上随机生成大量黑点,起干扰作用;  
  36.     for ($i = 0; $i < 80; $i++) {  
  37.         imagesetpixel($im, rand(0, $w), rand(0, $h), $black);  
  38.     }  
  39.     //将数字随机显示在画布上,字符的水平间距和位置都按一定波动范围随机生成  
  40.     $strx = rand(3, 8);  
  41.     for ($i = 0; $i < $num; $i++) {  
  42.         $strpos = rand(1, 6);  
  43.         imagestring($im, 5, $strx, $strpos, substr($code, $i, 1), $black);  
  44.         $strx += rand(8, 12);  
  45.     }  
  46.     imagepng($im);//输出图片  
  47.     imagedestroy($im);//释放图片所占内存  
  48. }
原创粉丝点击