专业编程基础技术教程

网站首页 > 基础教程 正文

菜鸟学PHP编程之验证码(php验证码识别)

ccvgpt 2024-07-26 00:44:01 基础教程 7 ℃

学习要点:

菜鸟学PHP编程之验证码(php验证码识别)

1.创建验证码函数

2.注册页面调用

3.JS点击局部刷新

4.将验证码包装成函数

5.编写函数注释

一. 创建验证码函数

验证码函数输入通用函数,将函数放入 global.func.php里。

//创建一个随机码

for($i=0;$i<4;$i++) {

$_nmsg .=dechex(mt_rand(0,15));

}

//将验证码保存到session里

$_SESSION['code'] =$_nmsg;

//设定验证码的图片的长度和高度

$_width =75;

$_height =25;

//创建图片

$_img =imagecreatetruecolor($_width,$_height);

//创建一个白色

$_white =imagecolorallocate($_img,255,255,255);

//填充背景

imagefill($_img,0,0,$_white);

//创建一个黑色的边框

$_black =imagecolorallocate($_img,100,100,100);

imagerectangle($_img,0,0,$_width-1,$_height-1,$_black);

//随机划线条

for($i=0;$i<6;$i++) {

$_rnd_color=imagecolorallocate($_img,mt_rand(0,255),mt_rand(0,255)

,mt_rand(0,255));

imageline($_img,mt_rand(0,75),mt_rand(0,75),mt_rand(0,75),mt_rand(0,75)

,$_rnd_color);

}

//随机打雪花

for($i=1;$i<100;$i++) {

imagestring($_img,1,mt_rand(1,$_width),mt_rand(1,$_height),"*",

imagecolorallocate($_img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)));

}

//输出验证码

for($i=0;$i<strlen($_SESSION['code']);$i++){

imagestring($_img,mt_rand(3,5),$i*$_width/4+mt_rand(1,10),

mt_rand(1,$_height/2),$_SESSION['code'][$i],

imagecolorallocate($_img,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200)));

}

//输出销毁

header("Content-Type: image/png");

imagepng($_img);

imagedestroy($_img);

二. 注册页面调用

code.php已经生成一张图片,所以,直接用图片插入的方式即可

<img src="code.php" id="code"/>

JS点击局部刷新

这段代码放入图片区域,可以自动刷新局部

onclick="javascript:this.src='code.php?tm='+Math.random()"

然后采用分离 JS的原则分离出去

二. 将验证码包装成函数

在核心函数库里创建一个_code函数,将验证码代码放入。

然后设置参数,最大的提供灵活性。

注意:如果没有任何设置,必须有默认值。

三. 编写函数注释

将_code()函数编写注释,让代码更清晰。

最近发表
标签列表