Home  >  Article  >  Backend Development  >  Detailed explanation of how PHP randomly generates image verification codes

Detailed explanation of how PHP randomly generates image verification codes

WBOY
WBOYOriginal
2016-07-25 08:52:44913browse
  1. session_start();
  2. //Randomly generate a string of verification codes
  3. function random($len) {
  4. $srcstr="ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
  5. mt_srand();
  6. $strs=" ";
  7. for($i=0;$i<$len;$i++) {
  8. $strs.=$srcstr[mt_rand(0,33)];
  9. }
  10. return ($strs);
  11. }
  12. $str =random(5); //Randomly generated string
  13. $width=60; //Width of the verification code image
  14. $height=25; //Height of the verification code image
  15. //Date in the past
  16. header(" Expires:Mon,26 Jul 1997 05:00:00 GMT");
  17. //always modified
  18. header("Last-Modified:".gmdate("D,d M Y H:i:s")."GMT");
  19. //HTTP/1.1
  20. header("Cache-Control:no-store,no-cache,must-revalidate");
  21. header("Cache-Control:post-check=0,pre-check=0",false );
  22. //HTTP/1.0
  23. header("Pragma:no-cache");
  24. header("Content-Type:image/png");
  25. $im=imagecreate($width,$height);
  26. $ back=imagecolorallocate($im,0xFF,0xFF,0xFF); //Background color
  27. $pix=imagecolorallocate($im,187,190,247); //Blurry point color
  28. $font=imagecolorallocate($im,41,163,238); //Font Color
  29. //Draw 1000 blurred points
  30. mt_srand();
  31. for($i=0;$i<1000;$i++) {
  32. imagesetpixel($im,mt_rand(0,$width),mt_rand(0 ,$height),$pix);
  33. }
  34. imagestring($im,5,7,5,$str,$font);//Draw a randomly generated string
  35. imagerectangle($im,0,0,$width -1,$height-1,$font);//Draw a 1px border around the verification code image
  36. imagepng($im);//Create a PNG format graphic
  37. imagedestroy($im);//Handle the image Deconstruct and release in memory space
  38. $_SESSION["auth_code"]=$str;
  39. ?>
Copy code

Example 2, PHP random verification code php generates simple verification code

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


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn