PHP实现验证码

本文详细介绍了一个使用PHP生成验证码的函数,包括如何设置验证码的宽度、高度、字符数量和类型,以及如何通过绘制背景、字符、干扰线和点来增强验证码的安全性和美观性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PHP生成验证码

<?php
	//1.宽高 字母 数字 字母数字混合线 干扰线 干扰点 背景色 字体的颜色
	verfify();
	function verfify( $width =100 ,$height = 40, $num = 5, $type = 1)
	{
		//1.准备画布
		$image = imagecreatetruecolor($width, $height);
		//2.生成颜色
		
		//3.需要的字符
		$string ='';
		switch($type)
		{
			case 1:
				$str = '0123456789';
				$string = substr(str_shuffle($str), 0 , $num);
			break;
			case 2:
				$arr = range('a','z');
				shuffle($arr);
				$tmp = array_slice($arr,0,$num);
				$string = join('',$tmp);
			break;
			case 3:
			$str = '0123456789abcdefjhijklmnopqrstuvwxyzABCDEFJHIJKLMNOPQRSTUVWXYZ';
			$string = substr(str_shuffle($str),0, $num);
			break;
			
		}
		//给背景填充浅色
		imagefilledrectangle($image,0,0,$width,$height,lightColor($image));
		//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);
		echo $string;
	}
	//浅颜色
	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));
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值