使用PHP怎么封装一个验证码类

介绍

这期内容当中小编将会给大家带来有关使用PHP怎么封装一个验证码类,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

代码如下:


& lt; ?
, PHP类ValidationCode {
,私人美元宽度;
,私人美元高度;
,私人codeNum美元;
,私人形象;美元,,//图像资源
,私人disturbColorNum美元;
,私人checkCode美元;
,函数__construct(宽度=80,身高=20美元,美元codeNum=4) {
,,=$ $ this→宽度宽度;
,,=$ $ this→高度高度;
,,$ this→codeNum=$ codeNum;
,,$ this→checkCode=$这→createCheckCode ();
,,美元数量=地板(宽*高/15美元);

,,如果数量比美元;240 - codeNum美元){
,,,$ this→disturbColorNum=240 - $ codeNum;
,,其他}{
,,,$ this→disturbColorNum=美元数量;
,,}

,}
,//通过访问该方法向浏览器中输出图像
,函数showImage ($ fontFace=啊? {
,,//第一步:创建图像背景
,,$ this→createImage ();
,,//第二步:设置干扰元素
,,$ this→setDisturbColor ();
,,//第三步:向图像中随机画出文本
,,$ this→outputText ($ fontFace);
,,//第四步:输出图像
,,$ this→outputImage ();
,}

,//通过调用该方法获取随机创建的验证码字符串
,函数getCheckCode () {
,,返回$ this→checkCode;
,}
,私有函数createImage () {
,,//创建图像资源
,,美元这→图像=imagecreatetruecolor ($ this→宽度、$ this→高度),
,,//随机背景色
,,(背景色=imagecolorallocate美元这→形象,兰德(225、255),兰德(225255),兰德(225、255));
,,//为背景添充颜色
,,imagefill ($ this→形象,0,0,背景色美元);
,,//设置边框颜色
,,(边界=imagecolorallocate美元这→形象,0,0,0),
,,//画出矩形边框
,,imagerectangle ($ this→形象,0,0,$ this→宽度,$ this→高为1,边境美元);
,}
,私人function setDisturbColor () {
,,($ i=0;i<这→美元disturbColorNum;$ + +){
,,,颜色=imagecolorallocate美元($ this→形象,兰德(0,255),兰德(0,255),兰特(0,255));
,,,imagesetpixel ($ this→形象,兰特(1,$ this→2),兰德(1,$ this→高度2),颜色)美元;
,,}
,,($ i=0;i<美元;10;$ + +){
,,,颜色=imagecolorallocate美元($ this→形象,兰德(200、255),兰德(200、255),兰德(200、255));
,,,imagearc ($ this→图片,兰德(-10,美元这→宽度),兰德(-10,美元这→高度),兰德(300),兰德(200),55岁,44岁的颜色)美元;
,,}
,}
,私有函数createCheckCode () {
//这里主要产生随机码,从2开始是为了区分1和l
,,代码=美元“23456789 abcdefghijkmnpqrstuvwxyzabcdefghijkmnpqrstuvwxyz"
,,$ string=& # 39; & # 39;;
,,($ i=0;美元我& lt;$ this→codeNum;$ + +){
,,,$字符代码=${兰特(0,strlen(代码)美元1)};
,,,字符串。美元=$字符;
,,}
,,返回字符串美元;
,}
,私有函数outputText ($ fontFace=啊? {
,,($ i=0;i<这→美元codeNum;$ + +){
,,,(fontcolor=imagecolorallocate美元这→形象,兰德(0,128),兰德(0,128),兰特(0,128));
,,,if ($ fontFace==啊? {
,,,,$字形大?兰德(3、5);
,,,,$ x=地板($ this→宽/$ this→codeNum) * + 3美元;
,,,,兰德($ y=0, $ this→height-15);
,,,,imagechar ($ this→形象,字形大小美元,$ x, y,美元$ this→checkCode{$我},fontcolor美元);
,,,其他}{
,,,,$字形大?兰德(12、16);
,,,,$ x=地板(($ this→width-8)/$ this→codeNum) *我+ 8美元;
,,,,$ y=兰特(字形大小+ 5美元,美元这→高度),
,,,,imagettftext ($ this→形象,字形大小美元,兰德(-30年,30),$ x, y,美元$ fontcolor fontFace美元,美元这→checkCode {$ i});
,,,}
,,}
,}
,私有函数outputImage () {
,,如果(imagetypes (),IMG_GIF) {
,,,头(“内容类型:图像/gif");
,,,imagepng ($ this→形象);
,,}else if (imagetypes (),IMG_JPG) {
,,,头(“内容类型:图像/jpeg");
,,,imagepng ($ this→形象);
,,}else if (imagetypes (),IMG_PNG) {
,,,头(“内容类型:图像/png");
,,,imagepng ($ this→形象);
,,}else if (imagetypes (),IMG_WBMP) {
,,,头(“内容类型:图像/vnd.wap.wbmp");
,,,imagepng ($ this→形象);
,,null

使用PHP怎么封装一个验证码类