萬盛學電腦網

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

ASP 限制同一 IP 僅能瀏覽一次:Cookie + 文字檔記錄法

應用場景

  • 投票系統防刷票
  • 問卷調查限制一 IP 一份
  • 優惠券領取防止重複領取

核心邏輯

  1. 檢查 Cookie 是否存在標記(IsBrow)。
  2. 若無 Cookie,讀取伺服器端文字檔(Iplist.txt)比對 IP。
  3. IP 不在清單 → 寫入清單、設定 Cookie、允許瀏覽。
  4. IP 已在清單或 Cookie 存在 → 關閉視窗或導向提示頁。

完整模組代碼(另存為 Check_Ip.asp)

<%
'/////////////////////////////////////////////////////
' 作用:一個 IP 地址只允許瀏覽本頁一次
' 作者: BaCde 2010-03-01
' 引用:<!-- #include file="Check_Ip.asp" -->
'/////////////////////////////////////////////////////

Dim Fso, ts, IpList, Cfs

' 設定 Cookie(一年有效)
Function SetCookie()
  Response.Cookies("IsBrow") = "Brow"
  Response.Cookies("IsBrow").Expires = Date + 365
End Function

' 記錄 IP 到文字檔
Function WriteIp(FileName, IpAddress)
  Set Fso = Server.CreateObject("Scripting.FileSystemObject")
  Set ts = Fso.OpenTextFile(Server.MapPath(FileName), 8, True) ' 8=ForAppending
  ts.WriteLine IpAddress
  ts.Close
  Set ts = Nothing
  Set Fso = Nothing
End Function

' 讀取 IP 清單
Function ReadIpList(FileName)
  Set Fso = Server.CreateObject("Scripting.FileSystemObject")
  If Not Fso.FileExists(Server.MapPath(FileName)) Then
    CreateFile "Iplist.txt"
    Exit Function
  End If
  Set ts = Fso.OpenTextFile(Server.MapPath(FileName))
  IpList = ts.ReadAll
  ts.Close
  Set ts = Nothing
  Set Fso = Nothing
  ReadIpList = IpList
End Function

' 建立空文字檔
Function CreateFile(FileName)
  Set Fso = Server.CreateObject("Scripting.FileSystemObject")
  Set Cfs = Fso.CreateTextFile(Server.MapPath(FileName))
  Cfs.Close
  Set Cfs = Nothing
  Set Fso = Nothing
End Function

'========== 主程式進入點 ==========
Dim clientIP, ipListContent
clientIP = Request.ServerVariables("REMOTE_ADDR")

' 1. 檢查 Cookie
If Request.Cookies("IsBrow") = "Brow" Then
  Response.Write ""
  Response.End
End If

' 2. 檢查伺服器端 IP 清單
ipListContent = ReadIpList("Iplist.txt")
If InStr(ipListContent, clientIP) > 0 Then
  Response.Write ""
  Response.End
End If

' 3. 通過檢查:記錄 IP、設定 Cookie
WriteIp "Iplist.txt", clientIP
SetCookie
%>

使用方式

在需保護的頁面最頂端引入:

<!-- #include file="Check_Ip.asp" -->

優缺點分析與改進建議

優點缺點改進方向
部署簡單,無需資料庫文字檔隨訪客增長,查詢效能下降改用 Application 變數或資料庫儲存 IP
雙重檢查Cookie 可被使用者清除/封鎖結合 Session 或指紋辨識
原始碼可讀性高無法防禦代理/NAT 共用 IP結合 User-Agent、Header 特徵判斷

進階版建議

  • 使用 Application.Lock/Unlock 同步寫入 Application 變數陣列,避免文字檔 I/O 瓶頸。
  • 加入時間戳記,定期清理過期 IP 記錄。
  • 整合至通用函式庫,支援自訂限制次數(如 1 天 5 次)。
copyright © 萬盛學電腦網 all rights reserved