yanzhengma.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="yan.php" method="post">
<input type="text" placeholder="输入验证码" name="code">
<img src="yanzheng.php" alt="">
<a href="javascript:reloadImage()">看不清?点我点我点我</a>
<input type="submit" value="提交">
</form>
<script>
function reloadImage() {
var img = document.getElementsByTagName("img")[0];
img.src = "yanzheng.php";
}
</script>
</body>
</html>
yanzheng.php
<?php
/**
* Created by PhpStorm.
* User: dllo
* Date: 16/8/12
* Time: 下午5:01
*/
header("Content-type:image/png");
session_start();
// 先删除原来session里的内容
//session_destroy();
unset($_SESSION["code"]);
$image = imagecreate(80,40);
imagecolorallocate($image,213,241,253);
$str = [];
for ($i = 0;$i < 6;$i++){
switch (rand(0,2)){
case 0:
// 数字
$str[$i] = chr(rand(48,57));
break;
case 1:
// 大写字母
$str[$i] = chr(rand(65,90));
break;
case 2:
// 小写字母
$str[$i] = chr(rand(97,122));
break;
}
$randColor = imagecolorallocate($image,rand(0,255),rand(0,255),rand(0,255));
imagechar($image,5,80 / 7 * ($i+1),10,$str[$i],$randColor);
}
$code = implode("",$str);
$_SESSION["code"] = $code;
//输入png格式的头像
imagepng($image);
yan.php
<?php
/**
* Created by PhpStorm.
* User: dllo
* Date: 16/8/12
* Time: 下午5:47
*/
header("Content-type:text/html;charset=utf-8");
session_start();
$_code = $_POST["code"];
if (strtoupper($_code) == strtoupper($_SESSION["code"])){
echo "验证成功";
}else{
echo "验证失败";
}