php随机生成图片验证码

我们在做表单验证的时候经常会用到图片验证码,图形验证码可以有效的防止一些不法分子利用软件恶意点击。虽然作用有限,但聊胜于无。
简单的代码实现:

//1、产生随机4位的字符串,array_merge:合并多个数组,range:随机函数
$str = array_merge(range("A", "Z"), range(0, 9), range("a", "z"));

//2、shuffle:将数组顺组打乱
shuffle($str);

//3、从数组中随机取出一个或多个单元(下标)
$indexS = array_rand($str, 4);

//4、取出随机下标中元素的值
$code = [];
foreach ($indexS as $index) {
    $code[] = $str[$index];
}

//5、创建一个空的画布,并分配颜色
$imgWidth = 100;
$imgHeight = 50;
$img = imagecreatetruecolor(100, 50);
//随机的背景颜色
$bgColor = imagecolorallocate($img, mt_rand(0, 60), mt_rand(0, 60), mt_rand(0, 60));

//6、画一矩形并填充颜色
imagefilledrectangle($img, 0, 0, $imgWidth, $imgHeight, $bgColor);
//给画布填充背景色也可以
//imagefill($img, 0, 0, $bgColor);

//7、向图像中写入一行TTF的文本(可以是汉字)
$x = 0; //文字开始的X轴位置
//随便一个字体文件都行,要绝对路径
$fontFile = "D:/My_study_papers/PHP/My_PHP/font/SIMLI.TTF";     //必须绝对路径
foreach ($code as $value) {
    //随机字体颜色
    $fontColor = imagecolorallocate($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
    imagettftext($img, 22, 0, $x, mt_rand(22,$imgHeight), $fontColor, $fontFile, $value);
    $x += mt_rand(10,33);
}

//8、绘制一些干扰的像素点
for ($i = 1; $i <= 200; $i++) {
    $dotColor = imagecolorallocate($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
    imagesetpixel($img,mt_rand(0,$imgWidth),mt_rand(0,$imgHeight),$dotColor);
}

//9、绘制一些干扰的线段
for ($i = 1; $i <= 10; $i++) {
    $lineColor = imagecolorallocate($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
    imageline($img,mt_rand(0,$imgWidth),mt_rand(0,$imgHeight),mt_rand(0,$imgWidth),mt_rand(0,$imgHeight),$lineColor);
}

//10、输出图像到浏览器
header("Content-Type:image/png");
imagepng($img);

//11、销毁图像资源
imagedestroy($img);

效果图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44790046/article/details/105993920
今日推荐