php生成图片验证码

首先,有一个在php.ini看看gd库是不是开启的,下一步,我们会考虑每一个细节的图像生成步骤.

php生成图片验证码实例代码如下:

  1. <?php
  2. //Send a generated image to the browser
  3. create_image();
  4. exit();
  5. function create_image()
  6. {
  7. //Let's generate a totally random string using md5
  8. $md5 = md5(rand(0,999));
  9. //We don't need a 32 character long string so we trim it down to 5
  10. $pass = substr($md5, 10, 5);
  11. //Set the image width and height
  12. $width = 100;
  13. $height = 20;
  14. //Create the image resource
  15. $image = ImageCreate($width, $height);
  16. //We are making three colors, white, black and gray
  17. $white = ImageColorAllocate($image, 255, 255, 255);
  18. $black = ImageColorAllocate($image, 0, 0, 0);
  19. $grey = ImageColorAllocate($image, 204, 204, 204);
  20. //Make the background black
  21. ImageFill($image, 0, 0, $black);
  22. //Add randomly generated string in white to the image
  23. ImageString($image, 3, 30, 3, $pass, $white);
  24. //Throw in some lines to make it a little bit harder for any bots to
  25. break
  26. ImageRectangle($image,0,0,$width-1,$height-1,$grey);
  27. imageline($image, 0, $height/2, $width, $height/2, $grey);
  28. imageline($image, $width/2, 0, $width/2, $height, $grey);
  29. //Tell the browser what kind of file is come in
  30. header("Content-Type: image/jpeg");
  31. //开源代码phpfensi.com
  32. //Output the newly created image in jpeg format
  33. ImageJpeg($image);
  34. //Free up resources
  35. ImageDestroy($image);
  36. }
  37. ?>

验证码调用方法,代码如下:

<img height="120" alt="Dynamically generated image" src="generate_image.php" width="200">