1、生成验证码
<?php
session_start();
$width = 100;
$length = 30;
$captch_code = '';
$image = imagecreatetruecolor($width, $length);
$color = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $color);
//产生随机数
for($i=0; $i<4; $i++)
{
$fontsize = 6; //?
$fontcolor = imagecolorallocate($image, rand(0,120), rand(0,120), rand(0,120));
$data = "abcdefghijklmnopqrstuvwxyz1234567890";
$fontcontent = substr($data,rand(0,strlen($data)),1);
$captch_code .= $fontcontent;
$x = ($i*$width/4) + rand($length/6,$length/3);
$y = rand($length/6,$length/3);
imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
}
$_SESSION['authcode'] = $captch_code;
//干扰点
for($i=0; $i<200; $i++)
{
$pointcolor = imagecolorallocate($image, rand(50,200), rand(50,200), rand(50,200));
imagesetpixel($image, rand(1,$width-1), rand(1,$width-1), $pointcolor);
}
//干扰线
for($i=0; $i<5; $i++)
{
$linecolor = imagecolorallocate($image, rand(80,220), rand(80,220), rand(80,220));
imageline($image, rand(1,$width-1), rand(1,$width/3-1), rand(1,$width-1), rand(1,$width/3-1), $linecolor);
}
header("content-type: image/png");
imagepng($image);
imagedestroy($image);
?>
2、登录处调用验证码
<li><label>验证码:</label>
<input name="code" type="text" class="inp1" maxlength="20" onFocus="document.getElementById('yzm').style.display='block'" />
<a href="javascript:void(0)" onClick="document.getElementById('captch_code').src='app/code_num.php?r='+Math.random()" title="看不清,换一个"><img id="captch_code" border="1" src="app/code_num.php?r=<?php echo rand();?>" height="35px" /></a>
</li>
3、php登录验证
if (isset($_POST['submit'])){
session_start();
if(($_POST['code']!=$_SESSION['authcode'])) {
exit('<script type="text/javascript">alert("验证码错误.");window.location.href="login.php";</script>');
}
$query = "select * from ds_user where name = '{$_POST['name']}' and password = '{$_POST['password']}'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) == 1){
echo "<script language="javascript">alert('登陆成功');window.location.href='/templates/admin/index.php';</script>";
}else{
echo "<script language="javascript">alert('密码错误');window.location.href='login.php';</script>";
}
}