首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 會員登入系統完整實作教學(含資料庫、驗證碼、CSS 排版)

     編輯:PHP 相關知識

PHP 會員登入系統完整實作教學

本文整理一套完整的 PHP 會員登入系統範例,包含前端表單、後端驗證、資料庫連線、圖形驗證碼與 CSS 排版,適合初學者參考架構與流程。

系統架構檔案說明

檔案功能說明
index.php登入頁面(HTML 表單 + CSS 引用)
check.php登入驗證處理(驗證帳密、驗證碼、Session 管理)
connect.phpMySQL 資料庫連線設定
piccheck.php圖形驗證碼產生器
css.css樣式表(版面置中、輸入框、按鈕、錯誤訊息樣式)

1. 登入頁面 index.php

<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>系統後台登入</title>
    <link href="css.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="box">
    <div id="denglu">
        <div id="pic">系統後台登入</div>
        <form action="check.php" method="post">
            <p>帳號:<input type="text" name="name" id="name" /><span class="must">*</span></p>
            <p>密碼:<input type="password" name="password" id="password" /><span class="must">*</span></p>
            <p>驗證碼:<input type="text" name="check" id="check" size="8" />
                <img src="piccheck.php" alt="驗證碼" onclick="this.src='piccheck.php?'+Date.now()" style="vertical-align:middle;cursor:pointer">
                <span class="must">*</span></p>
            <p class="form_button">
                <input type="submit" name="sub" id="sub" value="登入" />
                <input type="reset" name="unsub" id="unsub" value="重置" />
            </p>
        </form>
    </div>
</div>
</body>
</html>

2. 資料庫連線 connect.php

<?php
// 建議使用 PDO 或 mysqli,此處為教學示範舊版 mysql_* 函式(已棄用)
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'test';

$conn = mysqli_connect($host, $user, $pass, $dbname);
if (!$conn) {
    die('資料庫連線失敗: ' . mysqli_connect_error());
}
mysqli_set_charset($conn, 'utf8');
?>

注意:原始範例使用已移除的 mysql_* 函式,現代專案務必改用 mysqli 或 PDO,並採用預處理語句防止 SQL 注入。

3. 驗證碼產生 piccheck.php

<?php
session_start();
header('Content-Type: image/gif');

// 產生 4 碼驗證碼(數字+十六進位字母)
$code = '';
for ($i = 0; $i < 4; $i++) {
    $code .= rand(0, 1) ? dechex(rand(10, 15)) : rand(0, 9);
}
$_SESSION['pic'] = $code;

// 建立圖片
$image = imagecreatetruecolor(50, 18);
$bg = imagecolorallocate($image, 0, 0, 0);
$text_color = imagecolorallocate($image, rand(100, 255), rand(100, 255), rand(100, 255));

// 繪製文字(隨機位置、大小)
imagestring($image, 10, rand(1, 15), rand(1, 5), $code, $text_color);
imagegif($image);
imagedestroy($image);
?>

4. 登入驗證 check.php(核心邏輯)

<?php
session_start();
require_once 'connect.php';

$name = $_POST['name'] ?? '';
$password = $_POST['password'] ?? '';
$check = $_POST['check'] ?? '';

$errors = [];

// 驗證碼檢查
if (strtolower($check) !== strtolower($_SESSION['pic'] ?? '')) {
    $errors[] = '驗證碼錯誤';
}

// 帳密檢查(使用預處理語句防 SQL 注入)
if ($name && $password) {
    $stmt = $conn->prepare('SELECT password FROM admin WHERE username = ?');
    $stmt->bind_param('s', $name);
    $stmt->execute();
    $stmt->bind_result($hashed_password);
    $stmt->fetch();
    $stmt->close();

    // 假設資料庫儲存的是雜湊密碼(password_hash)
    if ($hashed_password && password_verify($password, $hashed_password)) {
        $_SESSION['admin_user'] = $name;
        header('Location: admin.php'); // 導向後台首頁
        exit;
    } else {
        $errors[] = '帳號或密碼錯誤';
    }
} else {
    $errors[] = '請輸入帳號與密碼';
}

// 失敗導回登入頁並顯示錯誤
$_SESSION['login_errors'] = $errors;
header('Location: index.php');
exit;
?>

5. CSS 樣式 css.css

@charset "utf-8";
body { background-color: #9CF; font-family: "Microsoft JhengHei", sans-serif; }
#denglu {
    width: 400px; margin: 50px auto; padding: 20px;
    background: #fff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
#pic { font-size: 18px; color: #F00; text-align: center; margin-bottom: 20px; }
#denglu form p { margin: 15px 0; display: flex; align-items: center; }
#denglu label { width: 80px; text-align: right; margin-right: 10px; }
#denglu input[type="text"], #denglu input[type="password"] {
    padding: 8px; border: 1px solid #ccc; border-radius: 4px; width: 200px;
}
.must { color: #F00; font-size: 12px; margin-left: 5px; }
.form_button { text-align: center; margin-top: 20px; }
.form_button input { padding: 8px 20px; margin: 0 5px; border: none; border-radius: 4px; cursor: pointer; }
.form_button input[type="submit"] { background: #007bff; color: #fff; }
.form_button input[type="reset"] { background: #6c757d; color: #fff; }

安全性強化重點

  1. 密碼雜湊:資料庫儲存 password_hash($pwd, PASSWORD_DEFAULT),驗證用 password_verify()。
  2. 預處理語句:使用 mysqli::prepare() 防止 SQL 注入。
  3. CSRF 防護:表單加入 <input type="hidden" name="csrf_token" value="">,驗證時比對。
  4. 登入失敗限制:記錄 IP 失敗次數,超過閾值暫時封鎖(可用 Redis 或資料表)。
  5. HTTPS:生產環境強制 HTTPS,避免帳密明文傳輸。

此範例展示基本架構,實際專案建議採用成熟框架(Laravel、Symfony)或認證套件,減少自行實作的安全風險。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved