ImageFileHandler.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace Webman\Captcha;
  3. /**
  4. * Handles actions related to captcha image files including saving and garbage collection
  5. *
  6. * @author Gregwar <g.passault@gmail.com>
  7. * @author Jeremy Livingston <jeremy@quizzle.com>
  8. */
  9. class ImageFileHandler
  10. {
  11. /**
  12. * Name of folder for captcha images
  13. * @var string
  14. */
  15. protected $imageFolder;
  16. /**
  17. * Absolute path to public web folder
  18. * @var string
  19. */
  20. protected $webPath;
  21. /**
  22. * Frequency of garbage collection in fractions of 1
  23. * @var int
  24. */
  25. protected $gcFreq;
  26. /**
  27. * Maximum age of images in minutes
  28. * @var int
  29. */
  30. protected $expiration;
  31. /**
  32. * @param $imageFolder
  33. * @param $webPath
  34. * @param $gcFreq
  35. * @param $expiration
  36. */
  37. public function __construct($imageFolder, $webPath, $gcFreq, $expiration)
  38. {
  39. $this->imageFolder = $imageFolder;
  40. $this->webPath = $webPath;
  41. $this->gcFreq = $gcFreq;
  42. $this->expiration = $expiration;
  43. }
  44. /**
  45. * Saves the provided image content as a file
  46. *
  47. * @param string $contents
  48. *
  49. * @return string
  50. */
  51. public function saveAsFile($contents)
  52. {
  53. $this->createFolderIfMissing();
  54. $filename = md5(uniqid()) . '.jpg';
  55. $filePath = $this->webPath . '/' . $this->imageFolder . '/' . $filename;
  56. imagejpeg($contents, $filePath, 15);
  57. return '/' . $this->imageFolder . '/' . $filename;
  58. }
  59. /**
  60. * Creates the folder if it doesn't exist
  61. */
  62. protected function createFolderIfMissing()
  63. {
  64. if (!file_exists($this->webPath . '/' . $this->imageFolder)) {
  65. mkdir($this->webPath . '/' . $this->imageFolder, 0755);
  66. }
  67. }
  68. }