自己写的面向过程php验证码

自学php一段时间了,看过别人写验证码的视频,总是过段时间就忘记了,发现自己还是理解的不深入。上班没事,自己写一段加强下理解记忆。代码如下:

<?php
header("content-type:image/jpeg");
//验证码实例
function getCode($len,$type=0){
	$code="";
	$arr=array(9,35,61);
	$str="0123456789abcedfghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	$nstr=substr($str,0,$arr[$type]);
	for($i=0;$i<$len;$i++){
		$code.=substr($nstr,rand(0,strlen($nstr)-1),1);	
	}
	return $code;
	
}
//1创建图像
$len=4;
$w=20*$len+8;
$h=30;
$code=getCode($len,1);
$img=imagecreatetruecolor($w,$h);
//验证码背景色
$bg=imagecolorallocate($img,220,220,220);
imagefill($img,0,0,$bg);
//要使用的颜色
$color[]=imagecolorallocate($img,255,0,0);
$color[]=imagecolorallocate($img,240,0,0);
$color[]=imagecolorallocate($img,0,0,14);
$color[]=imagecolorallocate($img,231,14,213);
$color[]=imagecolorallocate($img,14,70,231);
$colorlen=count($color);
//2添加干扰点
for($i=0;$i<=100;$i++){
		imagesetpixel($img,rand(0,$w),rand(0,$h),$color[rand(0,$colorlen)]);
}
//3添加干扰线
for($i=0;$i<3;$i++){
imageline($img,rand(0,$w),rand(0,$h),rand(0,$w),rand(0,$h),$color[rand(0,$colorlen)]);
}
//4将文字写入图像
for($i=0;$i<$len;$i++){
imagettftext($img,18,rand(-30,30),(20*$i)+8,24,$color[rand(0,$colorlen)],'arial.ttf',$code[$i]);
}
//输出图像
imagejpeg($img);
?>

  

原文地址:https://www.cnblogs.com/kongxs/p/3037682.html