php生成图片验证码,使用javascript点击图片刷新验证码,以及后台验证验证码是否正确

首先讲一下如何生成一张图片
创建一个图像应该完成以下四个步骤:
1、创建图像
2、绘制图像
3、输出图像
4、释放资源

生成一张图片的完整代码

<?php
header('Content-type:image/jpeg');//告诉浏览器要返回图片
// 一、创建图像
$img = imagecreatetruecolor(200, 200);//新建一个长和高都为200px的真彩图像

// 二、绘制图像
$color = imagecolorallocate($img, 50, 50, 50);//分配颜色
imagefill($img, 0, 0, $color);//区域填充

// 三、输出图像
imagejpeg($img);//输出图像

//四、释放资源
imagedestroy($img);
?>

下面是一个完整的验证码代码示例,使用javascript点击图片刷新验证码
先看效果,点击图片会进行刷新
在这里插入图片描述
生成一张随机的验证码图片的代码 yanzhengma.php

<?php
//创建一张验证码图片,用到图像处理的一些函数
header('Content-type:image/jpeg');
session_start();
$width = 90;//设置验证码宽度
$height = 30;//设施验证码高度
$element = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');//验证码的内容从这里面随机生成
$string = '';//验证码内容,需要初始化,如果不初始化是追加不上的
for ($i=0; $i < 5; $i++) { //生成5个随机的英文字符
	$string.=$element[rand(0,count($element)-1)];//加"."的意思是在后面追加字符
}
//将生成的验证码放进session
$_SESSION['string'] = $string;

$img = imagecreatetruecolor($width, $height);//创建图片
$colorBg = imagecolorallocate($img, rand(200,255), rand(200,255), rand(200,255));//设置颜色
$colorBorder = imagecolorallocate($img, rand(200,255), rand(200,255), rand(200,255));//边框颜色
$colorPix = imagecolorallocate($img, rand(100,200), rand(100,200),rand(100,200));//像素点颜色
$colorline = imagecolorallocate($img, rand(100,200), rand(100,200),rand(100,200));//设置线条颜色
$colorString = imagecolorallocate($img, rand(0,100), rand(0,100),rand(0,100));//设置验证码颜色
imagefill($img, 0, 0, $colorBg);//填充颜色
imagerectangle($img, 0, 0, $width-1, $height-1, $colorBorder);//设置边框

for ($i=0; $i <100 ; $i++) { //生成随机的像素点
	imagesetpixel($img, rand(0,$width-1), rand(0,$height-1), $colorPix);
}
for ($i=0; $i < 3 ; $i++) { //随机生成多条线
	imageline($img, rand(10,$width/2), rand(0,$height), rand($width/2,$width), rand(0,$height), $colorline);
}
imagestring($img, 14, rand(-2,5), rand(10,20), $string, $colorString);//将随机生成的字符串输出到图片中
// imagettftext(image, size, angle, x, y, color, fontfile, text);//这个函数和imagestring()函数差不多,但是它可以设置字体

imagejpeg($img);//输出图片
imagedestroy($img);//释放资源

前台代码

<label>验证码:</label><input style="width: 90px;" type="text" name="add_yanzhengma" id="add_yanzhengma">
<img id="user_refresh" src="yanzhengma.php" onclick="refresh()">
	<span id="user_yanzhengma" class="error">*</span><br><br>
	<input class="btn" type="submit" value="注册">

javascript代码

function refresh(){
			document.getElementById("user_refresh").src = "http://localhost/4.users/yanzhengma.php?tm="+Math.random();
		}

后台验证是否输入正确的验证码

//开启session
session_start();   
$yanzhengma =strtolower($_POST["add_yanzhengma"]);//接收用户输入的验证码转换成小写
$str = strtolower($_SESSION["string"]);//将随机生成的验证码转换成小写
if ($yanzhengma != $str) {
echo "<script type='text/javascript'>";
	echo "alert('验证码错误');";
	echo "history.back();";
	echo "</script>";
	}

发布了6 篇原创文章 · 获赞 10 · 访问量 3038

猜你喜欢

转载自blog.csdn.net/lemonminer/article/details/97398714