php(利用GD库生成验证码)

代码如下:

<?php
	
	verify();
	// 1 宽 高  字母 数字 字母数字混合 干扰线 干扰点 背景色 字体的颜色
function verify($width=100,$height=40,$num=5,$type=3)
{
    
    
		//1.准备画布
		$image = imagecreatetruecolor($width,$height);
		// 2.生成颜色(给背景填充浅色)
//imagefilledrectangle($image,0,0,$width,$height,lightColor($image));
		imagefill($image,0,0,lightColor($image));
		//3. 生成字符
		$string = '';
		switch($type){
    
    
			case 1:
				$str = '0123456789';
// str_shuffle函数可以打乱字符串的顺序,substr函数截取字符串
				$string = substr(str_shuffle($str),0,$num);
				break;
			case 2:
				$arr = range('a','z');
//shuffle函数打乱数组顺序,array_slice截取数组,join将数组连接为字符串
				shuffle($arr);
				$tmp = array_slice($arr,0,5);
				$string = join('',$tmp);
				break;		
			case 3:
				$str = '0123456789qwertyuiopasdfghjlkzxcvbnm
				ASDFGHJKLQWERTYUIOPZXCVBNM';
				$string = substr(str_shuffle($str),0,$num);
				break;
		}
		//4.开始写字
	for($i=0;$i<$num;$i++){
    
    
		$x = floor($width/$num)*$i;
		$y = mt_rand(10,$height-20);
		imagechar($image,5,$x,$y,$string[$i],deepColor($image));
	}
	//5.干扰线(点)
	for($i=0;$i<$num;$i++){
    
    
		imagearc($image,mt_rand(10,$width),
		mt_rand(10,$height),mt_rand(10,$width),mt_rand(10,$height),
		mt_rand(0,10),mt_rand(0,270),deepColor($image));
	}
	for($i=0;$i<50;$i++){
    
    
		imagesetpixel($image,mt_rand(0,$width),
		mt_rand(0,$height),deepColor($image));
	}
	//6.指定输出的类型
	header('Content-type:image/png');
	//7.准备输出图片
	imagepng($image);
	//8.销毁
	imagedestroy($image);
	
 
}
	//生成浅色
	function lightColor($image){
    
    
		return imagecolorallocate($image,mt_rand(130,255),
		mt_rand(130,255),mt_rand(130,255));
	}
//生成深色
	function deepColor($image){
    
    
		return imagecolorallocate($image,mt_rand(0,120),
		mt_rand(0,120),mt_rand(0,120));
	}
 
?>

用到的字符串函数和数组函数: str_shuffle函数可以打乱字符串的顺序,substr函数截取字符串。 shuffle函数打乱数组顺序,array_slice截取数组,join将数组连接为字符串。

用到的GD库函数: imagefill用来填充画布背景色。

在这里插入图片描述

imagefilledrectangle函数跟上面函数的用法相似。

在这里插入图片描述

imagechar函数用来在图上写字。

在这里插入图片描述

imagesetpixel函数用来画干扰点。imagearc函数用来画干扰线。

在这里插入图片描述

最终生成的随机验证码效果图如下:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_46456049/article/details/108589653