No Description

Captcha.php 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. class LtCaptcha
  3. {
  4. public $configHandle;
  5. public $storeHandle;
  6. public $imageEngine;
  7. public function __construct()
  8. {
  9. if (! $this->configHandle instanceof LtConfig)
  10. {
  11. if (class_exists("LtObjectUtil", false))
  12. {
  13. $this->configHandle = LtObjectUtil::singleton("LtConfig");
  14. }
  15. else
  16. {
  17. $this->configHandle = new LtConfig;
  18. }
  19. }
  20. }
  21. public function init()
  22. {
  23. if (!is_object($this->storeHandle))
  24. {
  25. $this->storeHandle = new LtStoreFile;
  26. $this->storeHandle->prefix = 'LtCaptcha-seed-';
  27. $this->storeHandle->init();
  28. }
  29. }
  30. public function getImageResource($seed)
  31. {
  32. if (empty($seed))
  33. {
  34. trigger_error("empty seed");
  35. return false;
  36. }
  37. if (!is_object($this->imageEngine))
  38. {
  39. if ($imageEngine = $this->configHandle->get("captcha.image_engine"))
  40. {
  41. if (class_exists($imageEngine))
  42. {
  43. $this->imageEngine = new $imageEngine;
  44. $this->imageEngine->conf = $this->configHandle->get("captcha.image_engine_conf");
  45. }
  46. else
  47. {
  48. trigger_error("captcha.image_engine : $imageEngine not exists");
  49. }
  50. }
  51. else
  52. {
  53. trigger_error("empty captcha.image_engine");
  54. return false;
  55. }
  56. }
  57. $word = $this->generateRandCaptchaWord($seed);
  58. $this->storeHandle->add($seed, $word);
  59. return $this->imageEngine->drawImage($word);
  60. }
  61. public function verify($seed, $userInput)
  62. {
  63. if ($word = $this->storeHandle->get($seed))
  64. {
  65. $this->storeHandle->del($seed);
  66. return $userInput === $word;
  67. }
  68. else
  69. {
  70. return false;
  71. }
  72. }
  73. protected function generateRandCaptchaWord()
  74. {
  75. $allowChars = $this->configHandle->get("captcha.allow_chars");
  76. $length = $this->configHandle->get("captcha.length");
  77. $allowedSymbolsLength = strlen($allowChars) - 1;
  78. $captchaWord = "";
  79. for ($i = 0; $i < $length; $i ++)
  80. {
  81. $captchaWord .= $allowChars[mt_rand(0, $allowedSymbolsLength)];
  82. }
  83. return $captchaWord;
  84. }
  85. }