php 字母和数字验证码

时间:2023-03-09 21:21:41
php 字母和数字验证码

//验证码

<?php
//实现简单的验证码 //session_start
session_start();
//画布
$image = imagecreatetruecolor(100, 30);
//设置填充颜色
$bgcolor = imagecolorallocate($image, 255, 255, 255);
//填充
imagefill($image, 0, 0, $bgcolor); //随机数据
//session
$captcha_code = '';
for ($i = 0; $i < 4; $i++) {
$fontsize = 5;
$fontcolor = imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
$data = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
// echo strlen($data);
// echo substr($data,61,1);
$font = substr($data, mt_rand(0, strlen($data) - 1), 1);
$captcha_code .= $font;
$width = ($i * 100) / 4 + mt_rand(5, 10);
$height = mt_rand(5, 10);
//添加
imagestring($image, $fontsize, $width, $height, $font, $fontcolor);
}
//保存到session
$_SESSION['authcode'] = $captcha_code;
//干扰
//像素点
for ($i = 0; $i < 200; $i++) {
$pixcolor = imagecolorallocate($image, mt_rand(20, 200), mt_rand(20, 200), mt_rand(20, 200));
imagesetpixel($image, mt_rand(0, 99), mt_rand(0, 29), $pixcolor);
} //线
for ($i = 0; $i < 4; $i++) {
$linecolor = imagecolorallocate($image, mt_rand(50, 220), mt_rand(50, 220), mt_rand(50, 220));
imageline($image, mt_rand(0, 99), mt_rand(0, 29), mt_rand(0, 99), mt_rand(0, 99), $linecolor);
}
//输出
header('Content-type: image/png');
imagepng($image);
//销毁
imagedestroy($image);

//验证表单

<?php
if (isset($_REQUEST['authcode'])) {
session_start();
//判断
if (strtolower($_REQUEST['authcode'] == strtolower($_SESSION['authcode']))) {
echo '恭喜你输入正确!';
} else {
echo '输入失败!';
}
exit();
}
?>
<html>
<head>
<title>验证码提交</title>
</head>
<body>
<form action="./form.php" method="post">
<p>验证码:<img src="./code01.php" id="captcha_img" alt="验证码" width="100" height="30" border="1px"></p>
<a href="javascript:void(0)" onclick="document.getElementById('captcha_img').src='./code01.php?r='+Math.random()">看不清?</a>
<p>
<label for="authcode">请输入图片中的内容: </label>
<input type="text" name="authcode" id="authcode"/>
</p> <p><input type="submit" value="submit"/></p>
</form>
</body>
</html>