萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP 經典:使用者註冊範例 (VBScript + Access)

資料庫設計 (Access .mdb)

欄位型別/長度說明
idAutoNumber主鍵
usernameText(16)使用者帳號
passwordText(32)MD5 32位加密後密碼
addtimeDateTime註冊時間

完整註冊頁面 (index.asp)

<%@ Language=VBScript CodePage=65001 %>
<%
'--- 連線設定 ---
Dim conn, connStr, dbPath
dbPath = Server.MapPath("aspdb.mdb")
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath

'--- 表單送出處理 ---
If Request.Form("btnSubmit") <> "" Then
    Dim username, pwd, pwd2, rs, sql
    username = Trim(Request.Form("username"))
    pwd = Trim(Request.Form("password"))
    pwd2 = Trim(Request.Form("password2"))

    If pwd <> pwd2 Then
        Response.Write ""
        Response.End
    End If

    Set conn = Server.CreateObject("ADODB.Connection")
    conn.Open connStr

    ' 檢查帳號是否存在
    Set rs = Server.CreateObject("ADODB.Recordset")
    sql = "SELECT COUNT(*) FROM userinfo WHERE username='" & Replace(username, "'", "''") & "'"
    rs.Open sql, conn, 1, 1
    If rs(0) > 0 Then
        Response.Write ""
        rs.Close: Set rs = Nothing
        conn.Close: Set conn = Nothing
        Response.End
    End If
    rs.Close: Set rs = Nothing

    ' 寫入新帳號 (password 為保留字需用 [])
    Dim pwdHash : pwdHash = GetMD5(pwd) ' 假設有 MD5 函式
    conn.Execute "INSERT INTO userinfo ([username],[password],[addtime]) VALUES ('" & username & "','" & pwdHash & "',NOW())"

    conn.Close: Set conn = Nothing
    Response.Write ""
End If
%>

<!DOCTYPE html>
<html><head><title>使用者註冊</title></head><body>
<form method="post" action="index.asp">
  用戶名:<input name="username" maxlength="16" required /><br/>
  密碼:<input name="password" type="password" maxlength="16" required /><br/>
  確認密碼:<input name="password2" type="password" maxlength="16" required /><br/>
  <button type="submit" name="btnSubmit">註冊</button>
</form>
</body></html>

關鍵安全補強 (原碼缺失項)

  • SQL Injection 防護:使用參數化查詢 (ADODB.Command) 或至少 `Replace(username, "'", "''")` 轉義單引號。
  • 密碼雜湊:原碼明文儲存,**必須**改用 MD5/SHA256 + Salt (VBScript 需引入 CAPICOM 或自行實作)。
  • 資源釋放:`rs.Close` / `Set rs = Nothing` / `conn.Close` / `Set conn = Nothing` 四步驟不可省略,否則連線洩漏導致服務器資源耗盡。
  • 錯誤處理:加入 `On Error Resume Next` 搭配 `Err.Number` 判斷,避免 500 錯誤洩漏資訊。

現代化建議

Classic ASP 已停止主流支援,新專案強烈建議遷移至 **ASP.NET Core** + **Entity Framework Core** + **SQL Server / PostgreSQL**,享有型別安全、依賴注入、非同步、跨平台等現代化優勢。

copyright © 萬盛學電腦網 all rights reserved