博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PHP验证码
阅读量:4612 次
发布时间:2019-06-09

本文共 2235 字,大约阅读时间需要 7 分钟。

设计一个验证码类,在需要的时候可以随时调用

验证码类,保存为ValidateCode.class.php

1 
font = './latha.ttf';//注意字体路径要写对,否则显示不了图片17 }18 //生成随机码19 private function createCode() {20 $_len = strlen($this->charset)-1;21 for ($i=0;$i<$this->codelen;$i++) {22 $this->code .= $this->charset[mt_rand(0,$_len)];23 }24 }25 //生成背景26 private function createBg() {27 $this->img = imagecreatetruecolor($this->width, $this->height);28 $color = imagecolorallocate($this->img, mt_rand(157,255), mt_rand(157,255), mt_rand(157,255));29 imagefilledrectangle($this->img,0,$this->height,$this->width,0,$color);30 }31 //生成文字32 private function createFont() {33 $_x = $this->width / $this->codelen;34 for ($i=0;$i<$this->codelen;$i++) {35 $this->fontcolor = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));36 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]);37 }38 }39 //生成线条、雪花40 private function createLine() {41 //线条42 for ($i=0;$i<6;$i++) {43 $color = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));44 imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);45 }46 //雪花47 for ($i=0;$i<100;$i++) {48 $color = imagecolorallocate($this->img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));49 imagestring($this->img,mt_rand(1,5),mt_rand(0,$this->width),mt_rand(0,$this->height),'*',$color);50 }51 }52 //输出53 private function outPut() {54 header('Content-type:image/png');55 imagepng($this->img);56 imagedestroy($this->img);57 }58 //对外生成59 public function doimg() {60 $this->createBg();61 $this->createCode();62 $this->createLine();63 $this->createFont();64 $this->outPut();65 }66 //获取验证码67 public function getCode() {68 return strtolower($this->code);69 }70 }

注意:第16行中,要修改字体的路径,否则字体图片无法显示

实现,保存为captcha.php

1 session_start();2 require './ValidateCode.class.php';  //先把类包含进来,实际路径根据实际情况进行修改。3 $_vc = new ValidateCode();  //实例化一个对象4 $_vc->doimg();  5 $_SESSION['authnum_session'] = $_vc->getCode();//验证码保存到SESSION中

页面使用

转载自:

转载于:https://www.cnblogs.com/HuangWj/p/4369278.html

你可能感兴趣的文章
软件工程第一次作业补充
查看>>
N76E003---输入捕获
查看>>
poj 1094 Sorting It All Out(拓扑排序)
查看>>
acdream B - 郭式树 (水题 卡cin,cout, 卡LL)
查看>>
BMP图像格式
查看>>
python的匿名函数lambda解释及用法
查看>>
c#遍历Dictionary使用KeyValuePair
查看>>
defineProperties属性的运用==数据绑定
查看>>
关于 IOS 发布的点点滴滴记录(一)
查看>>
《EMCAScript6入门》读书笔记——14.Promise对象
查看>>
CSS——水平/垂直居中
查看>>
Eclipse连接mysql数据库jdbc下载(图文)
查看>>
Python中Selenium的使用方法
查看>>
三月23日测试Fiddler
查看>>
20171013_数据库新环境后期操作
查看>>
poj 1654 && poj 1675
查看>>
运维派 企业面试题1 监控MySQL主从同步是否异常
查看>>
Docker 版本
查看>>
poj 1753 Flip Game
查看>>
在深信服实习是怎样的体验(研发测试岗)
查看>>