PHP验证码的产生和生成验证码程序

由于注册的时候常常会用到注册码来防止机器恶意注册,这里我发表一个产生png图片验证码的基本图像,很简陋但思想很清晰:

1、产生一张png的图片

2、为图片设置背景色

3、设置字体颜色和样式

4、产生4位数的随机的验证码

5、把产生的每个字符调整旋转角度和位置画到png图片上

6、加入噪点和干扰线防止注册机器分析原图片来恶意注册

7、输出图片

8、释放图片所占内存

authcode.php文件,代码如下:

  1. <?php
  2. session_start ();
  3. header ( 'content-type: image/png' );
  4. //创建图片
  5. $im = imagecreate($x=130,$y=45 );
  6. $bg = imagecolorallocate($im,rand(50,200),rand(0,155),rand(0,155)); //第一次对 imagecolorallocate() 的调用会给基于调色板的图像填充背景色
  7. $fontcolor = imagecolorallocate ( $im, 255, 255, 255 ); //字体颜色
  8. $fontstyle = 'rock.ttf'; //字体样式,这个可以从c:windows onts文件夹下找到,我把它放到和authcode.php文件同一个目录,这里可以替换其他的字体样式
  9. //产生随机字符
  10. for($i = 0; $i < 4; $i ++) {
  11. $randasciinumarray = array (rand(48,57),rand(65,90));
  12. $randasciinum = $randasciinumarray [rand ( 0, 1 )];
  13. $randstr = chr ( $randasciinum );
  14. imagettftext($im,30,rand(0,20)-rand(0,25),5+$i*30,rand(30,35),$fontcolor,$fontstyle,$randstr);
  15. $authcode .= $randstr;
  16. }
  17. $_session['authcode'] = $randfourstr;//用户和用户输入的验证码做比较
  18. //干扰线
  19. for ($i=0;$i<8;$i++){
  20. $linecolor = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
  21. imageline ($im,rand(0,$x),0,rand(0,$x),$y,$linecolor);
  22. }//开源代码phpfensi.com
  23. //干扰点
  24. for ($i=0;$i<250;$i++){
  25. imagesetpixel($im,rand(0,$x),rand(0,$y),$fontcolor);
  26. }
  27. imagepng($im);
  28. imagedestroy($im);
  29. ?>