1. 程式人生 > >PHP實現帶有驗證碼的登陸註冊

PHP實現帶有驗證碼的登陸註冊

開發工具

Wampserver

WampServer就是Windows下 Apache+Mysql+PHP整合安裝環境,即在window下的apache、php和mysql的伺服器軟體,通俗的說,就是它集成了php開發所需要的資料庫軟體,伺服器和PHP直譯器,這將很大程度上減少開發的時間

Navicat是一套快速、可靠的資料庫管理工具,是以直覺化的圖形使用者介面而建的。將資料庫更加形象直觀的展現在你的面前,避免的命令列的大黑框,讓你可以以安全並且簡單的方式建立、組織、訪問並共用資訊

程式碼展示

login.html

<!DOCTYPE html>
<html lang="en"> <head> <meta charset="utf-8"> </head> <link rel="stylesheet" href="./css/login.css"> <body> <!-- 實現在表單頂部登陸和註冊頁面的轉換 --> <header id="header" class="header"> <a href="register.html">
註冊</a> <a href="login.html">登陸</a> </header> <div class="content"> <label><input type="text" name="username" placeholder="使用者名稱" value="" ></label> <label><input type="password" name="password"
placeholder="密碼" value="">
</label> <label><input type="text" value="" name="checkNum" placeholder="請輸入驗證碼"></label> <img src="validcode.php" style="width:100px;height:25px;" id="code"/> <a href="javascript:changeCode()">看不清,換一張</a> <button class="btn" id="submit">提交</button> </div> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript"> //點選圖片更新驗證碼 function changeCode() { document.getElementById("code").src = "validcode.php?id=" + Math.random(); } //敲擊空格提交請求 $(document).keyup(function(event){ if(event.keyCode ==13){ $("#submit").trigger("click"); } }); //對於請求進行非空驗證 $("#submit").click(function(){ var username = $("input[name='username']").val(); var password = $("input[name='password']").val(); var checkNum = $("input[name='checkNum']").val(); if(username==undefined||username===''){ alert("使用者名稱不能為空"); return; } if(password==undefined||password==''){ alert("密碼不能為空"); return; } if(checkNum==undefined||checkNum==''){ alert("請輸入驗證碼"); return; } //將請求提交到後臺 $.post( 'login.php', {"username":username,"password":password,"checkNum":checkNum}, function (result) { //對後臺返回資訊進行處理 if (result.indexOf('success')!=-1) { window.location.href="https://www.baidu.com"; //登陸成功跳轉到百度首頁 } else { alert(result); } }) }) </script> </body> </html>

login.css

head,body{
    margin: 0;
    padding: 0;
}


#header{
    width: 400px;
    height: 40px;
    margin:auto;
    background-color: red;
    margin-top: 500px;
    border-top-right-radius: 8px;
    border-top-left-radius: 8px;
}

#header a{
    float: left;
    margin-left: 100px;
    text-decoration: none;
}

.content{
    width: 400px;
    height: 200px;
    margin-left: auto;
    margin:auto;
    margin-top: 0px;
    border-bottom-right-radius: 8px;
    border-bottom-left-radius: 8px;

}
.content label input {
    width: 395px;
    height: 50px;
    margin-top: 0px;
}

login.php

<?php
session_start();
$con=mysql_connect("localhost:3306","資料庫使用者名稱(預設為:root)","你的資料庫密碼");
if(!$con){
    die('Clould not connect:'.mysql_errno());
}


$salt = 'left';
//對前臺傳來的資料進行特殊字元的轉義,能夠有效的防止sql注入等
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string(md5($salt.$_POST['password']));
$checkNum = $_POST["checkNum"];
mysql_select_db("mysql",$con);
$feedback = "賬戶密碼錯誤";

if($checkNum==$_SESSION["validcode"]){

   $SQL="select username from login where username='$username' and password='$password'"; 
   $result=mysql_query($SQL);
   $rows=mysql_num_rows($result);
   if($rows!==1){
       echo $feedback;
   }
   else{
       $feedback="success"; 
       echo $feedback;
   }
}
?>

register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<link rel="stylesheet" href="./css/register.css">
<body>
<header id="header" class="header">
    <a href="register.html">註冊</a>
    <a href="login.html">登陸</a>
</header>

<div class="content">
    <label><input type="text" name="username" placeholder="使用者名稱" value=""></label>
    <label><input type="password" name="password" placeholder="密碼" value=""></label>
    <label><input type="password" name="confirm" placeholder="確認密碼"></label>
    <label><input type="text" value="" name="checkNum" placeholder="請輸入驗證碼"></label>
    <img src="validcode.php" style="width:100px;height:25px;" id="code"/>
    <a href="javascript:changeCode()">看不清,換一張</a>
    <button class="btn" id="submit">提交</button>

</div>

<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">

    function changeCode() {

        document.getElementById("code").src = "validcode.php?id=" + Math.random();
    }


    $(document).keyup(function(event){ 
                if(event.keyCode ==13){ 
                $("#submit").trigger("click"); 
                } 
            });


    $("#submit").click(function () {
        var username = $("input[name='username']").val();
        var password = $("input[name='password']").val();
        var password_confirm = $("input[name='confirm']").val();
        var checkNum = $("input[name='checkNum']").val();


        if (username == undefined || username === '') {
            alert("使用者名稱不能為空");
            return;
        }
        if (password == undefined || password == '') {
            alert("密碼不能為空");
            return;
        }
        if (password_confirm == undefined || password_confirm == '') {
            alert("請確認密碼");
            return;
        } else if (password_confirm !== password) {
            alert("兩次輸入的密碼不一致");
            return;
        }
        if (checkNum == undefined || checkNum == '') {
            alert("請輸入驗證碼");
            return;
        }
        $.post(
                'register.php',
                {"username": username, "password": password,"checkNum":checkNum},
                function (result) {
                    if (result.indexOf('註冊成功')!=-1) {
                        window.location.href="login.html";
                        alert("註冊成功");
                    } 
                    if (result.indexOf('該使用者已經存在')!=-1) {
                        window.location.href="register.html";
                        alert("該使用者已經存在");
                    } 
                })
    })

</script>
</body>
</html>

register.css

head,body{
    margin: 0;
    padding: 0;
}


#header{
    width: 400px;
    height: 40px;
    margin:auto;
    background-color: red;
    margin-top: 500px;
    border-top-right-radius: 8px;
    border-top-left-radius: 8px;
}

#header a{
    float: left;
    margin-left: 100px;
    text-decoration: none;
}

.content{
    width: 400px;
    height: 250px;
    margin-left: auto;
    margin:auto;
    margin-top: 0px;
    border-bottom-right-radius: 8px;
    border-bottom-left-radius: 8px;
}
.content label input {
    width: 395px;
    height: 50px;
    margin-top: 0px;
}

register.php

 <?php


session_start();
$salt = 'left';
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string(md5($salt.$_POST['password']));
$checkNum = $_POST["checkNum"];
$feedback = "註冊失敗";

if($checkNum==$_SESSION["validcode"]){
    $con=mysql_connect("localhost:3306","","");

    if(!$con){
    die('Clould not connect:'.mysql_errno());
    }
    mysql_select_db("mysql",$con); 

    $SQL="select * from login where username='$username'";
    $result=mysql_query($SQL);
    $rows=mysql_num_rows($result);
    if($rows>=1){  
        $feedback="該使用者已經存在";
    }                                                        
    else{  
        $sql_insert = "insert into login (username,password) 
        values ("."'$username',"."'$password')" ;  
                    $res_insert = mysql_query($sql_insert);   
                    if($res_insert)  
                    {  
                       $feedback="註冊成功";  
                    }  
                    else  
                    {  
                       $feedback="註冊失敗";  
                    }  
                }  
}

echo $feedback;
mysql_close();
?>

vaildcode.php

<?php   

    header("Content-Type:image/png");  

    //開啟session  
    session_start();  

    //隨機4個數字  
    $code = "";  
    $arr = array();  
    for($i=0;$i<4;$i++){  

        $arr[$i] = rand(0,9);  
        $code .= (string)$arr[$i];  
    }  

    //設定入session中,方便比對  
    $_SESSION["validcode"] = $code;  

    //開始繪圖  
    $width = 100;  
    $height = 25;  
    $img = imagecreatetruecolor($width,$height);  

    //填充背景色  
    $backcolor = imagecolorallocate($img,0,0,0);  
    imagefill($img,0,0,$backcolor);  

    //獲取隨機較深顏色   
    for($i=0;$i<4;$i++){  

        $textcolor = imagecolorallocate($img,rand(50,180),rand(50,180),rand(50,180));   
        imagechar($img,12,7+$i*25,3,(string)$arr[$i],$textcolor);  
    }  

    //顯示圖片  
    imagepng($img);  

    //銷燬圖片  
    imagedestroy($img);  
?>  

最後將register.css和login.css檔案放在專案的css資料夾下即可,圖片為專案目錄專案目錄

這是資料庫的表設計
表格式

接下來,我們就將整個專案的資料夾放在wamp安裝目錄的www資料夾下即可,例如博主的wamp安裝在E盤,專案名為csdn,則目錄為
執行目錄
然後我們就啟動wampserver軟體,等它由紅色變為綠色後,在瀏覽器輸入http://localhost/csdn/login.html
這裡寫圖片描述
大功告成;

注意事項:

  • Ajax和form提交請求的區別?
    Ajax在提交、請求、接收時,都是非同步進行的,網頁不需要重新整理;必須要使用JS來實現,不啟用JS的瀏覽器,無法完成該操作;
    Form提交則是新建一個頁面,哪怕是提交給自己本身的頁面,也是需要重新整理的;不需要JS

原始碼地址


這裡寫圖片描述
掃碼關注作者個人技術公眾號,有關技術問題後臺回覆即可,不定期將有學習資源分享