####html页面,没加入CSS代码:
<form action="login.php" method="post"> <input type="text" placeholder="账号" name="id"/> <input type="password" name="password"/> <input type="password" name="authcode"/> <img id="captcha_img" border='1' src='./captcha.php?r=<?php echo rand(); ?>' style="width:100px; height:100%;" > <a style="color:yellow" href="javascript:void(0)" οnclick="document.getElementById('captcha_img').src='./captcha.php?r='+Math.random()">换一个?</a> <input type="submit" value="立即登陆" name="submit"/> <input type="submit" value="注册" name="zhuce"/> </form>123456789
####利用正则表达式过滤一些非法字符:$pattern = ‘/’|<|>|"|#|&|%/’;
####防范SQL注入攻击使用PDO类连接数据库,这里我用的是mysql,地址和端口我就用本地的了。
try { $db = new PDO('mysql:host=127.0.0.1:3306;dbname=name','username','password'); }catch (PDOException $e) { echo "<script>alert('数据库连接出现问题,请稍后再试');window.location.href='login.php';</script>"; }123456
###对用户输入的用户名和密码进行校验。
if (isset($_POST['submit'])) { if(isset($_REQUEST['authcode'])){ session_start(); //strtolower()小写函数 if(strtolower($_REQUEST['authcode'])== jiemi(jiemi($_SESSION['authcode']))){ $id=strip_tags(trim(htmlspecialchars($_POST['id']))); $password=htmlspecialchars(strip_tags($_POST['password'])); if (empty($id) || empty($password)) { echo "<script>alert('账号密码不能为空');window.location.href='login.php';</script>"; } else if (preg_match_all($pattern, $id) || preg_match_all($pattern, $password)) { echo "<script>alert('存在非法字符,请重新输入');window.location.href='login.php';</script>"; } else if(strlen($password)>21) { echo "<script>alert('请使您的密码长度小于21位!');window.location.href='login.php';</script>"; } else{ $search = $db->prepare("select username from information where id={$id} and password='$password'"); $search->execute(); $arr = $search->fetch(); $username = $arr[0]; if ($username != null) { $db = null; setcookie('id',jiami($id)); echo "<script>alert('欢迎用户{$username},即将跳转至主页,请稍后...');window.location.href='index.php';</script>"; } else { $db = null; echo "<script>alert('登陆失败,请检查您输入的账号密码是否正确');window.location.href='login.php';</script>"; } } }else{ //提示以及跳转页面 echo "<script language=\"javascript\">"; echo "alert('验证码输入错误!请重新输入');"; echo "document.location=\"./login.php\""; echo "</script>"; } exit(); }12345678910111213141516171819202122232425262728293031323334353637
###验证码的实现将在下一篇文章中给出。这里是用PDO实现防SQL注入,并对cookie进行加密,加密算法是自己写的,这里暂不透露,不过SQL内部没有进行加密,所以还是有数据泄露风险的。而验证码纯粹是为了防止穷举密码攻击。
###这里还留了一个漏洞没有防范,不知道有没有眼尖的小伙伴发现呢?