• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

PHP验证码类ValidateCode解析

php 搞代码 4年前 (2022-01-22) 12次浏览 已收录 0个评论

这篇文章主要为大家详细解析了PHP验证码类ValidateCode,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

PHP解析验证码类

1.开始

在网上看到使用PHP写的ValidateCode生成验证码类,感觉不错,特拿来分析学习一下。

2.类图

  //随机因子  private $charset = 'abcdefghjkmnprstuvwxyzABCDEFGJKMNPRSTUVWXYZ23456789';  private $code;  private $codeLen = 4;  private $width = 130;  private $heigh = 50;  private $img;//图像  private $font;//字体  private $fontsize = 20;

$charset 是随机因子,这里是去掉了几个不容易区分的字符,如字母"i,l,o,q",数字"0,1"。有必要可以加入一些中文或其他字符或算式等。

$codeLen表示验证码长度,常见4位。

3.2构造函数,设置验证码字体,生成一个真彩色图像img

public function __construct()  {    $this->font = ROOT_PATH.'/font/Chowderhead.ttf';    $this->img = imagecreatetruecolor($this->width, $this->heigh);  }

3.3从随机因子中随机抽取4个字符,作为$code验证码.

//生成随机码  private function createCode()  {    $_len = strlen($this->charset) - 1;    for ($i = 0; $i < $this->codeLen; $i++) {      $this->code .= $this->charset[mt_rand(0, $_len)];    }  }

3.4生成验证码背景色.

//生成背景  private function createBg()  {$color = imagecolorallocate($this->img, mt_rand(157, 255), mt_rand(157, 255), mt_rand(157, 255));    imagefilledrectangle($this->img, 0, $this->heigh, $this->width, 0, $color);  }

其中mt_rand(157, 255),目的是随机取比较浅的颜色。

3.5在图像上生成文字.

//生成文字  private function createFont()  {    $_x = $this->width / $this->codeLen;    $_y = $this->heigh / 2;    for ($i = 0; $i < $this->codeLen; $i++) {      $color = imagecolorallocate($this->img, mt_rand(0, 156), mt_rand(0, 156<p>+本文来源gao!%daima.com搞$代*!码9网(</p><strong>搞gaodaima代码</strong>), mt_rand(0, 156));      imagettftext($this->img, $this->fontsize, mt_rand(-30, 30), $_x * $i + mt_rand(3, 5), $_y + mt_rand(2, 4), $color, $this->font, $this->code[$i]);    }  }

在图像上生成验证码文字,主要考虑文字在图像上的位置和每一个文字颜色。

控制第n个文字的x轴位置 = (图像宽度 / 验证码长度) * (n-1) + 随机的偏移数; 其中n = {d1….n}

控制第n个文字的y轴位置 = 图像高度 / 2 + 随机的偏移数;

mt_rand(0, 156) 随机取文字颜色,0-156目的是取比较深的颜色。

mt_rand(-30, 30) 随机的文字旋转。

3.6在图像上生成线条和雪花

//生成线条,雪花  private function createLine()  {    for ($i = 0; $i < 15; $i++) {      $color = imagecolorallocate($this->img, mt_rand(0, 156), mt_rand(0, 156), mt_rand(0, 156));      imageline($this->img, mt_rand(0, $this->width), mt_rand(0, $this->heigh), mt_rand(0, $this->width), mt_rand(0, $this->heigh), $color);    }    for ($i = 0; $i < 150; $i++) {      $color = imagecolorallocate($this->img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));      imagestring($this->img, mt_rand(1, 5), mt_rand(0, $this->width), mt_rand(0, $this->heigh), '#', $color);    }  }

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:PHP验证码类ValidateCode解析

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址