zl程序教程

您现在的位置是:首页 >  其他

当前栏目

前端登陆案例php

2023-09-11 14:16:16 时间

  

 

  index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>login</h1>
    <button><a href="./login.html">go to login</a></button>
</body>
</html>

 

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="">
        <h3 style="display:none;">login failed</h3>
        username: <input type="text" name="username" autocomplete="off"><br>
        password: <input type="text" name="password" autocomplete="off"><br>
        <button>submitf</button>
    </form>
    <script>
        const username=document.querySelector('input[name=username]')
        const password=document.querySelector('input[name=password]')
        const form=document.querySelector('form')
        const h3=document.querySelector('h3')
        
        form.addEventListener('submit',e=>{
            e.preventDefault()
            if(!username.value || !password.value) return alert('form incomplete')
            const xhr=new XMLHttpRequest()
            xhr.open('POST','./login.php')
            xhr.onload=function(){
                
                const {message,code}=JSON.parse(xhr.responseText)
                console.log(message,code)
                if(code===0){
                    window.location.href='./index.html'
                }else if(code!==0){
                    h3.style.display='block'
                }
            }
            xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')
            xhr.send(`username=${username.value}&password=${password.value}`)
        })
    </script>
</body>
</html>

 

login.php

<?php
    $username=$_POST['username'];
    $password=$_POST['password'];

    $link=mysqli_connect('localhost','root','cruces','abate');
    $sql="select * from users where username='$username' and password='$password'";
    $result=mysqli_query($link,$sql);
    $data=mysqli_fetch_all($result);

    if(count($data)){
        session_start();
        // $_SESSION['login']=1;
        // $_SESSION['username']=$data[0]['username'];
        $arr=array(
            "message"=>"success",
            "code"=>0
        );
    }else{
        $arr=array(
            "message"=>"failed",
            "code"=>1
        );
    }

    echo json_encode($arr);

?>