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>