php实现的验证码文件类实例

这篇文章主要介绍了php实现的验证码文件类,实例分析了php生成验证码文件的技巧,非常具有实用价值,需要的朋友可以参考下,本文实例讲述了php实现的验证码文件类。分享给大家供大家参考,具体如下:

  1. <?php
  2. /**
  3. * @file
  4. * @version 1.0
  5. * @author 网海浪子
  6. * @brief 验证码文件类
  7. *
  8. */
  9. class CCheckCodeFile
  10. {
  11. //验证码位数
  12. private $mCheckCodeNum = 4;
  13. //产生的验证码
  14. private $mCheckCode = '';
  15. //验证码的图片
  16. private $mCheckImage = '';
  17. //干扰像素
  18. private $mDisturbColor = '';
  19. //验证码的图片宽度
  20. private $mCheckImageWidth = '80';
  21. //验证码的图片宽度
  22. private $mCheckImageHeight = '20';
  23. /**
  24. *
  25. * @brief 输出头
  26. *
  27. */
  28. private function OutFileHeader()
  29. {
  30. header ("Content-type: image/png");
  31. }
  32. /**
  33. *
  34. * @brief 产生验证码
  35. *
  36. */
  37. private function CreateCheckCode()
  38. {
  39. $this->mCheckCode = strtoupper(substr(md5(rand()),0,$this->mCheckCodeNum));
  40. return $this->mCheckCode;
  41. }
  42. /**
  43. *
  44. * @brief 产生验证码图片
  45. *
  46. */
  47. private function CreateImage()
  48. {
  49. $this->mCheckImage = @imagecreate ($this->mCheckImageWidth,$this->mCheckImageHeight);
  50. imagecolorallocate ($this->mCheckImage, 200, 200, 200);
  51. return $this->mCheckImage;
  52. }
  53. /**
  54. *
  55. * @brief 设置图片的干扰像素
  56. *
  57. */
  58. private function SetDisturbColor()
  59. {
  60. for ($i=0;$i<=128;$i++)
  61. {
  62. $this->mDisturbColor = imagecolorallocate ($this->mCheckImage, rand(0,255), rand(0,255), rand(0,255));
  63. imagesetpixel($this->mCheckImage,rand(2,128),rand(2,38),$this->mDisturbColor);
  64. }
  65. }
  66. /**
  67. *
  68. * @brief 设置验证码图片的大小
  69. *
  70. * @param $width 宽
  71. *
  72. * @param $height 高
  73. *
  74. */
  75. public function SetCheckImageWH($width,$height)
  76. {
  77. if($width==''||$height=='')return false;
  78. $this->mCheckImageWidth = $width;
  79. $this->mCheckImageHeight = $height;
  80. return true;
  81. }
  82. /**
  83. *
  84. * @brief 在验证码图片上逐个画上验证码
  85. *
  86. */
  87. private function WriteCheckCodeToImage()
  88. {
  89. for ($i=0;$i<=$this->mCheckCodeNum;$i++)
  90. {
  91. $bg_color = imagecolorallocate ($this->mCheckImage, rand(0,255), rand(0,128), rand(0,255));
  92. $x = floor($this->mCheckImageWidth/$this->mCheckCodeNum)*$i;
  93. $y = rand(0,$this->mCheckImageHeight-15);
  94. imagechar ($this->mCheckImage, 5, $x, $y, $this->mCheckCode[$i], $bg_color);
  95. }
  96. }
  97. /**
  98. *
  99. * @brief 输出验证码图片
  100. *
  101. */
  102. public function OutCheckImage()
  103. {
  104. $this ->OutFileHeader();
  105. $this ->CreateCheckCode();
  106. $this ->CreateImage();
  107. $this ->SetDisturbColor();
  108. $this ->WriteCheckCodeToImage();
  109. imagepng($this->mCheckImage);
  110. imagedestroy($this->mCheckImage);
  111. }
  112. }
  113. $c_check_code_image = new CCheckCodeFile();
  114. //$c_check_code_image ->SetCheckImageWH(100,50);
  115. //设置显示验证码图片的尺寸
  116. $c_check_code_image ->OutCheckImage();
  117. ?>