0%

[技能檢定]題組二 步驟6 建置會員登入/登出功能

我們先來製作登入/登出功能,因為本題組有不少功能會使用登入狀態來區分使用者可以使用的功能,依據題意,這邊要使用ajax來製作會比較適當,也比較好呈現題目要求的各項提示訊息。

  1. ./front/ 目錄下建立 login.php,並撰寫登入頁需要的頁面HTML碼
  2. 使用 <fieldset><legend></legend></fieldset> 來產生群組外框標題字的效果
    login.php
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <fieldset>
    <legend>會員登入</legend>
    <table>
    <tr>
    <td class='clo'>帳號</td>
    <td><input type="text" name="acc" id="acc"></td>
    </tr>
    <tr>
    <td class='clo'>密碼</td>
    <td><input type="password" name="pw" id="pw"></td>
    </tr>
    <tr>
    <td>
    <input type="button" value="登入" onclick="login()">
    <input type="reset" value="清除" onclick="clean()">
    </td>
    <td>
    <a href="?do=forget">忘記密碼</a> |
    <a href="?do=reg">尚未註冊</a>
    </td>
    </tr>
    </table>
    </fieldset>

  1. 登入和清除功能,我們都不透過form表單,所以要自行撰寫js程式來完成

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    function login() {
    // 取得帳號輸入框的值
    let acc=$("#acc").val()
    // 取得密碼輸入框的值
    let pw=$("#pw").val()
    // 發送 POST 請求到 chk_acc.php 檢查帳號是否存在
    $.post('./api/chk_acc.php', {acc}, (res) => {
    // 如果回傳的結果為 0,表示查無帳號
    if (parseInt(res) == 0) {
    alert("查無帳號")
    } else {
    // 發送 POST 請求到 chk_pw.php 檢查帳號密碼是否正確
    $.post('./api/chk_pw.php', { acc,pw },(res) => {
    // 如果回傳的結果為 1,表示密碼正確
    if (parseInt(res) == 1) {
    // 如果帳號為 'admin',導向後台頁面
    if ($("#acc").val() == 'admin') {
    location.href = 'back.php'
    } else {
    // 否則導向首頁
    location.href = 'index.php'
    }
    } else {
    alert("密碼錯誤")
    }
    })
    }
    })
    }

    function clean(){
    //清除帳號和密碼欄位的值
    $("input[type='text'],input[type='password']").val("");
    }
  2. 建立 ./api/chk_acc.php,並撰寫驗證帳號的方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    include_once "../base.php";

    //利用count來檢查是否帳號已存在
    $res=$User->count(['acc'=>$_POST['acc']]);
    //回傳檢查的結果
    if($res>0){
    echo 1;
    }else{
    echo 0;
    }

    //簡化的寫法
    echo $User->count(['acc'=>$_POST['acc']]);
  3. 建立 ./api/chk_pw.php,並撰寫驗證帳號密碼的方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    //使用count來進行帳號與密碼的檢查
    $res=$User->count($_POST);

    //如果帳密正確,建立session
    if($res){
    $_SESSION['user']=$_POST['acc'];
    }

    //回傳結果
    echo $res;
  4. 在資料表中匯入素材指定的帳號資料

由於版型素材提供的css並不是全部都可用,因此如果要畫面美觀的話,很多的css要自己寫,
美化的工作建議可以等功能都做完時再回頭來改就可以了。