Implement backend administrator login function
In the previous chapter, we selected the background login page and successfully added the verification code to the login.html file of the login page. And created the database table admin, and added a test data of user name and password. In this section we will implement the login function.
Let’s first look at a simple function implementation flow chart:
With the flow chart, you will have an idea. Follow the idea and you will know what you need to do step by step. .
First of all, we need to introduce the public database file: config.php
Get the data through POST. Use the trim() function to remove unnecessary spaces, etc.
$username = trim($_POST["username"]);//用户名 $password = trim($_POST["password"]);//密码 $code = $_POST["code"]; //验证码
Verify whether the user name and password are filled in, and the verification code is matched.
if($username == "") { echo"<script type='text/javascript'>alert('请填写用户名');location='login.html'; </script>"; } if($password == "") { //echo "请填写用户名<br>"; echo"<script type='text/javascript'>alert('请填写密码');location='login.html'; </script>"; } if($code != $_SESSION['authcode']) { echo "<script type='text/javascript'>alert('验证码错误!');location='login.html';</script>"; }
Take the submitted username and password and search in the database to see if this username and password exist.
$sql = "select * from admin where username='".$username."' and password='".$password."'"; $result = mysqli_query($link, $sql); $rows = mysqli_fetch_array($result); if($rows) { //echo "验证成功!<br>"; $expire_time=time()+7200; setcookie('admin_id',$rows['id'],$expire_time); setcookie('username',$rows['username'],$expire_time); echo "<script type='text/javascript'>alert('登陆成功');location='index.php';</script>"; } else { //echo "用户名或者密码错误<br>"; echo "<script type='text/javascript'>alert('用户名或者密码错误');location='login.html';</script>"; //echo "<a href='login.html'>返回</a>"; }
After successful login, enter the main interface of the background, this is achieved Administrator login function.