失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > php 随机码类 php随机类型验证码

php 随机码类 php随机类型验证码

时间:2023-10-14 13:48:07

相关推荐

php 随机码类 php随机类型验证码

开发使用验证码的意义就是为了区别操作者是人还是机器,防止自动脚本对服务器造成灾难性的攻击

目前有各种各样的验证码种类,譬如:静态字符验证码、算术验证码、拖拽验证码、识别文字或识别物品验证码(高级),下面介绍随机切换算术或字符验证码

一、使用函数列表

(1)imagecreatetruecolor:创建画布

(2)imagecolorallocate:为画布分配颜色

(3)imagefill:画布填充颜色

(4)imagesetpixel:设置干扰点

(5)imageline:设置干扰线

(6)imagestring:水平地画一行字符串

(7)imagepng:以 png格式将图像输出到浏览器或文件

(8)imagedestroy:销毁图片

二、实现流程

创建画布 -> 为画布定义背景颜色 -> 填充背景颜色 -> 设置干扰点 -> 设置干扰线 -> 把字符串填充到画布 -> 设置header向浏览器输出图片 -> 输出图片到浏览器 -> 销毁图片

三、实现代码

define("WIDTH", 200);

define("HEIGHT", 50);

//1.创建画布

$image = imagecreatetruecolor(WIDTH, HEIGHT);

//2.为画布定义背景颜色

$bgcolor = imagecolorallocate($image, 255, 255, 255);

//3.填充背景颜色

imagefill($image, 0, 0, $bgcolor);

//4.设置干扰点

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

$pointcolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));

imagesetpixel($image, mt_rand(0, WIDTH), mt_rand(0, HEIGHT), $pointcolor);

}

//5.设置干扰线

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

$linecolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));

imageline($image, mt_rand(0, WIDTH), mt_rand(0, HEIGHT), mt_rand(0, WIDTH), mt_rand(0, HEIGHT), $linecolor);

}

$type=mt_rand(0,1);

if($type==0){

$num1=mt_rand(0, 99);

$num2=mt_rand(0, 99);

$cal="+-";

$captcha=$num1.$cal[mt_rand(0, strlen($cal)-1)].$num2.‘=‘;

$captchaLen=strlen($captcha);

$distance=WIDTH/2.0/$captchaLen;

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

// 字体颜色

$fontcolor = imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));

// 设置字体内容

$fontcontent = substr($captcha, $i, 1);

// 设置字符的xy坐标

$x = WIDTH/2.0- $distance*$captchaLen/2+$i* $distance;

$y = mt_rand(5, 30);

// 6.把字符串填充到画布

imagestring($image,30, $x, $y, $fontcontent, $fontcolor);

}

}else{

$captcha=‘2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY‘;

$captchaLen=4;

$distance=WIDTH/2.0/$captchaLen;

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

// 字体颜色

$fontcolor = imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));

// 设置字体内容

$fontcontent = $captcha[mt_rand(0, strlen($captcha)-1)];

// 设置字符的xy坐标

$x = WIDTH/2.0- $distance*$captchaLen/2+$i* $distance;

$y = mt_rand(5, 30);

// 6.把字符串填充到画布

imagestring($image,30, $x, $y, $fontcontent, $fontcolor);

}

}

//7.向浏览器输出图片头信息

header(‘content-type:image/png‘);

//8.输出图片到浏览器

imagepng($image);

//9.销毁图片

imagedestroy($image);

如果觉得《php 随机码类 php随机类型验证码》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。