为什么要做?

因为上次编程猫助手每天访问量1000+,被官方点名之后,编程猫里有许多大佬找到了我,加入了很多相关组织,应邀(有奖金)写了一个后端,用来登录,今天就来分享一下源代码,也留着后面用,说不定何时又需要登录了呢

登录思路

我们要实现登录验证就要用到cookie,读取之类的校验又需要mysql,下面我分享我的思路:

登录.php 发送请求给 captcha.php

catpcha.php 接收后 连接数据库 -- 找到数据表 -- 寻找指定用户名 -- 校验数据 -- 取随机数字 -- 存入数据库 -- 设置cookie

欧耶搞定!可是看起来如此简单,实现起来很难,接下来解剖源代码

源代码

登录.html :

 

<form role="form" action="##" onsubmit="return false" method="post" id="login">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">账号</span>
</div>
<input type="text" class="form-control" name="user" placeholder="请输入账号">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">密码</span>
</div>
<input type="password" class="form-control" name="pwd" placeholder="请输入密码">
</div>
<button type="button" class="btn btn-secondary" onclick="login()">登录</button>
</form>

<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>

<script type="text/javascript">
function login(){
$.ajax({
type: "POST",
url: "captcha.php",
data: $('#login').serialize(),
success: function (data) {
if (data.result == "200") {
location.href='index.php';
}else{
}
setTimeout('closesctips()', 2000);
}
error : function() {
}
});
}
</script>

如你所见,我采用了行内一般使用的jq进行post,这个html十分简单,没啥技术含量,接下来就到了我们的验证环节了

captcha.php:

header("Content-type:application/json");//声明头部信息
$u1 = trim($_POST["user"]);
$u2 = trim($_POST["pwd"]);
$servername = "localhost";
$username = "数据库用户名";
$password = "数据库密码";
$dbname = "数据库";
$con = new mysqli($servername, $username, $password, $dbname);
$result = mysqli_query($con,"SELECT * FROM NumWHERE name='".$u1."'" );
while($row = mysqli_fetch_array($result))
{
$user = $row['name'];
$pass = $row['pass'];
$new = $row['cookie'];
}
if ($user==$u1 and $pass==$u2) {
session_start();
$num=mt_rand(0,8848);//哈哈8848钛金手机
mysqli_query($con,"UPDATE Num SET cookie=".$num." WHERE name='".$user ."'");
$_SESSION['login.yes'] = $num;
$result = array(
"result" => "200",
"msg" => "登录成功");
}else{
$result = array("result" => "104","msg" => "账号或密码错误"
);
}}
echo json_encode($result,JSON_UNESCAPED_UNICODE);
?>

说一下,其中的$num变量即是我们的cookie内容,就是用它来验证,然后,我们就到了读取cookie来确认用户的环节了:

session_start();//一定要写在最前面,要不然会报错
$servername = "localhost";
$username = "账户";
$password = "密码";
$dbname = "名字";
$con = new mysqli($servername, $username, $password, $dbname);

$cookie = $_SESSION['login.yes'];
if ($con->connect_error) {
die("连接失败: " . $conn->connect_error);
}

if ($cookie==''){

}else{
$result = mysqli_query($con,"SELECT * FROM Num
WHERE cookie='".$cookie."'" );
while($row = mysqli_fetch_array($result))
{
$name = $row['name'];
$pass = $row['pass'];
$cookie = $row['cookie'];
echo '用户名为'.$name.'哦~';
}
}

 

现在,我们就完美的解决啦!我要写作业了,博主还有好多作业没写啊啊啊


一个初一的垃圾