php原生生成验证码类

it2023-02-12  57

<?php # 创建一个验证码生成类 // Create the image class Verify { private $fontfile = 'E:\phpstudy_pro\WWW\php7\simkai.ttf'; public $width = 120; # 画板宽度 public $height = 50; # 画板高度 public $red = 25;# color red 色值 public $blue = 10;# color blue 色值 public $green = 30;# color green 色值 private $img = null; public function index() { session_start(); # 创建一个空白图像 $im = imagecreatetruecolor($this->width, $this->height); $this->img = $im; //分配一个随机色 $color = imagecolorallocate($im, $this->red,$this->green,$this->blue); # 文字颜色 $white = imagecolorallocate($im, 255, 255, 255); //画一矩形并填充随机色 imagefilledrectangle($im, 0, 400, 300, 0, $color); if(!file_exists($this->fontfile)) { echo "字体文件不存在"; die; } $str = $this->random(); for($i=0;$i <= strlen($str);$i++) { imagettftext($im, 24, mt_rand(0,5), $i*20, 35, $white, $this->fontfile,substr($str,strlen($str)-$i,1)); } $this->createLine(); header('Content-type:image/png'); imagepng($im); imagedestroy($im); } # 生成随机数 protected function random($str = null) { if(is_null($str)){ $str = mt_rand(0000,9999); } if(strlen($str) != 4){ $str = $str.mt_rand(1,9); } # 存储到session中 $_SESSION['code'] = strrev($str); $_SESSION['time'] = time() + 30; return $str; } //生成线条、雪花 private function createLine() { //线条 for ($i = 0; $i < 10; $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->height), mt_rand(0, $this->width), mt_rand(0, $this->height), $color); } //雪花 for ($i = 0; $i < 20; $i++) { $color = imagecolorallocate($this->img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); imagestring($this->img, mt_rand(1, 5), mt_rand(0, $this->width), mt_rand(0, $this->height), '*', $color); } } } $verfiy = new Verify(); $verfiy->index();

好好学习,

最新回复(0)