PHP 登录页生成验证码,验证登录

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>";
}
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 验证码就是把一串随机产品的数字动态生成一幅图片,再加上干扰元素。此时用户可以通过肉眼能识别里面的数字或者字符...
    dy2903阅读 6,551评论 0 7
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,351评论 0 33
  • 【启动图】 //先添加一个线性布局 width=-1 height=-1 orientation=vertical...
    Mr_洛寒阅读 4,371评论 0 3
  • 这是一篇寻人启事,寻找那个叫阿绍的少年。 这是大碗第五次梦见他了。 个子高高瘦瘦,有些婴儿肥,眼睛大大睫毛长长,还...
    雷小嫖阅读 4,938评论 0 0
  • 用途:在客户端的磁盘上以很小的文件保存一定量的数据。 cookie的内容document.cookie='name...
    Miss____Du阅读 11,726评论 1 10