Heim  >  Artikel  >  Backend-Entwicklung  >  php随机生成图片验证码方法详解

php随机生成图片验证码方法详解

WBOY
WBOYOriginal
2016-07-25 08:52:44913Durchsuche
  1. session_start();
  2. //随机生成验证码的字符串
  3. function random($len) {
  4. $srcstr="ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
  5. mt_srand();
  6. $strs="";
  7. for($i=0;$i $strs.=$srcstr[mt_rand(0,33)];
  8. }
  9. return ($strs);
  10. }
  11. $str=random(5); //随机生成的字符串
  12. $width=60; //验证码图片的宽度
  13. $height=25; //验证码图片的高度
  14. //Date in the past
  15. header("Expires:Mon,26 Jul 1997 05:00:00 GMT");
  16. //always modified
  17. header("Last-Modified:".gmdate("D,d M Y H:i:s")."GMT");
  18. //HTTP/1.1
  19. header("Cache-Control:no-store,no-cache,must-revalidate");
  20. header("Cache-Control:post-check=0,pre-check=0",false);
  21. //HTTP/1.0
  22. header("Pragma:no-cache");
  23. header("Content-Type:image/png");
  24. $im=imagecreate($width,$height);
  25. $back=imagecolorallocate($im,0xFF,0xFF,0xFF); //背景色
  26. $pix=imagecolorallocate($im,187,190,247); //模糊点颜色
  27. $font=imagecolorallocate($im,41,163,238); //字体色
  28. //绘制1000个模糊作用的点
  29. mt_srand();
  30. for($i=0;$i imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$pix);
  31. }
  32. imagestring($im,5,7,5,$str,$font);//绘制随机生成的字符串
  33. imagerectangle($im,0,0,$width-1,$height-1,$font);//在验证码图像周围绘制1px的边框
  34. imagepng($im);//建立一张PNG格式图形
  35. imagedestroy($im);//将图片handle解构,释于内存空间
  36. $_SESSION["auth_code"]=$str;
  37. ?>
复制代码

例2,php随机验证码 php生成简单的验证码

  1. $image_width=140;
  2. $image_height=50;
  3. srand(microtime()*10000);
  4. for($i=0;$i $number.=dechex(rand(0,15));
  5. }
  6. $check=$number;
  7. $im=imagecreate($image_width,$image_height);
  8. imagecolorallocate($im,255,255,255);
  9. for($i=0;$i $font=rand(40,80);
  10. $x=rand(1,8)+$image_width*$i/4;
  11. $y=rand(1,$image_height/4);
  12. $color=imagecolorallocate($im,rand(0,100),rand(0,150),rand(0,200));
  13. imagestring($im,$font,$x,$y,$check[$i],$color);
  14. }
  15. imagepng($im);
  16. imagedestroy($im);
  17. ?>
复制代码


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn