PHP脚本生成验证码——附源码

本文介绍了一种使用PHP生成验证码的方法,并提供了完整的代码实现。该验证码不仅能够在网页中展示,还会保存在session中以便后续验证。同时,文章还提供了一个简单的验证流程。

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

PHP验证码
生成验证码的代码,此页面可以直接运行,生成的验证码不但能在页面中看到,而且会保存在session中。

<?php 
// 1、函数创建一个100,30的底图
// 2、对地图加入颜色区域
// 3、设置内容和字符之间的距离
// 4、添加干扰元素
// 5、增加干扰线
// 6、销毁图片
session_start();
//创建长100,高30的画布  默认为黑色背景
$image = imagecreatetruecolor(100,30);
//为画布生成随机底色(未填充)
$bgcolor = imagecolorallocate($image, mt_rand(70,200), mt_rand(110,195), mt_rand(50,150));
//将生成的随机底色填充到画布中
imagefill($image, 0, 0, $bgcolor);
$code = '';
//生成随机字符
for($i = 0; $i < 4; $i++){
	$fontsize = 6;//字体大小,不可以设置太大,设置太大也不会生效
	//为字体生成随机颜色
	$fontcolor = imagecolorallocate($image, rand(10,110),rand(10,110),rand(10,110));
	$string = "qwertyuiopasdfghjklzxcvbnmQAZWSXEDCRFVTGBYHNUJMIKOLP0123456789";
	$fontcontent = substr($string,rand(0,(strlen($string)-1)),1);//生成随机字符
	$code .= $fontcontent;
	$x = ($i * (100/4) + rand(5,10));//生成字符的x坐标  后面的随机数是用来保证字符不会贴着边
	$y = rand(5,10);//生成随机字符的y坐标
	//将随机字符着色并放在图片的x,y坐标处
	imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);
}
$_SESSION['code'] = $code;

//增加干扰字符点
for($i = 0; $i <= 200; $i++){
	$pointcolor = imagecolorallocate($image,rand(50,150), rand(50,150), rand(50,150));//点的颜色
	imagesetpixel($image, rand(1,99), rand(1,99), $pointcolor);//将点放到底图上
}

//增加干扰字符线
for($i = 0; $i < 5; $i++){
	$linecolor = imagecolorallocate($image,rand(50,220),rand(50,220),rand(50,220));
	imageline($image, rand(1,99), rand(1,29), rand(1,99), rand(1,29), $linecolor);
}

//设置生成的图片类型
header("content-type:image/png");
//将图片显示到浏览器
imagepng($image);
//销毁图片,防止占用内存
imagedestroy($image);
var_dump($code);
 ?>

验证码的简单验证

<?php 
if(!empty(($_POST['code']))){
	session_start();
	header("Content-type:text/html;chatset=utf-8");
	if(strtolower($_POST['code']) == strtolower($_SESSION['code'])){
		echo "<h3>验证码正确</h3>";
	}else{
		echo "<h3>验证码错误</h3>";
	}
	exit;
}

 ?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<form action="#" method="post">
		<p>
			<img src="test1.php" alt="验证码" onclick="this.src=this.src+'?'+ Math.random();"/>
			<!-- <img src=“验证码文件路径"  onclick = "this.src='验证码路径?'+Math.random()"/>其他同理! -->
		</p>
		<p>
			请输入验证码:<input type="text" name="code">
		</p>
		<p><input type="submit" value="提交"></p>
		
	</form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

anansec

打赏是我创作路上的加油剂!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值