PageRenderTime 61ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/application/libraries/Captcha.php

https://github.com/601186678/compare--php
PHP | 87 lines | 69 code | 8 blank | 10 comment | 5 complexity | b55102a869afbfb8b2837258282a71ce MD5 | raw file
  1. <?php
  2. if (!defined('BASEPATH'))
  3. exit('No direct script access allowed');
  4. class Captcha
  5. {
  6. private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789'; //随机因子
  7. private $code; //验证码
  8. private $codelen = 4; //验证码长度
  9. private $width = 300; //宽度
  10. private $height = 50; //高度
  11. private $img; //图形资源句柄
  12. private $font; //指定的字体
  13. private $fontsize = 30; //指定字体大小
  14. private $fontcolor; //指定字体颜色
  15. //构造方法初始化
  16. public function __construct($config)
  17. {
  18. $this->font = empty($config['font_file']) ? './css/fonts/elephant.ttf' : $config['font_file'];
  19. $this->createBg();
  20. $this->createCode();
  21. }
  22. //生成随机码
  23. private function createCode()
  24. {
  25. $_len = strlen($this->charset) - 1;
  26. for ($i = 0; $i < $this->codelen; $i++) {
  27. $this->code .= $this->charset[mt_rand(0, $_len)];
  28. }
  29. }
  30. //生成背景
  31. private function createBg()
  32. {
  33. $this->img = imagecreatetruecolor($this->width, $this->height);
  34. $color = imagecolorallocate($this->img, mt_rand(157, 255), mt_rand(157, 255), mt_rand(157, 255));
  35. imagefilledrectangle($this->img, 0, $this->height, $this->width, 0, $color);
  36. }
  37. //生成文字
  38. private function createFont()
  39. {
  40. $_x = $this->width / $this->codelen;
  41. for ($i = 0; $i < $this->codelen; $i++) {
  42. $this->fontcolor = imagecolorallocate($this->img, mt_rand(0, 156), mt_rand(0, 156), mt_rand(0, 156));
  43. imagettftext($this->img, $this->fontsize, mt_rand(-30, 30), $_x * $i + mt_rand(1, 5), $this->height / 1.4, $this->fontcolor, $this->font, $this->code[$i]);
  44. }
  45. }
  46. //生成线条、雪花
  47. private function createLine()
  48. {
  49. //线条
  50. for ($i = 0; $i < 6; $i++) {
  51. $color = imagecolorallocate($this->img, mt_rand(0, 156), mt_rand(0, 156), mt_rand(0, 156));
  52. imageline($this->img, mt_rand(0, $this->width), mt_rand(0, $this->height), mt_rand(0, $this->width), mt_rand(0, $this->height), $color);
  53. }
  54. //雪花
  55. for ($i = 0; $i < 100; $i++) {
  56. $color = imagecolorallocate($this->img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
  57. imagestring($this->img, mt_rand(1, 5), mt_rand(0, $this->width), mt_rand(0, $this->height), '*', $color);
  58. }
  59. }
  60. //输出
  61. private function outPut()
  62. {
  63. header('Content-type:image/png');
  64. imagepng($this->img);
  65. imagedestroy($this->img);
  66. }
  67. //对外生成
  68. public function doimg()
  69. {
  70. $this->createLine();
  71. $this->createFont();
  72. $this->outPut();
  73. }
  74. //获取验证码
  75. public function getCode()
  76. {
  77. return strtolower($this->code);
  78. }
  79. }