利用 Cookie 限制使用者提交頻率是簡單有效的防刷手段。本文分析原始碼中的邏輯缺陷,提供修正版本並延伸至 Session、資料庫等更可靠的替代方案。
<%
' ❌ 原始碼邏輯錯誤
MyVar = Request.Cookies("starttime")
If MyVar = "" Then
Response.Cookies("starttime") = Time() ' 只存時間,不含日期
Response.Cookies("starttime").Expires = DateAdd("n", 1, Now()) ' 1 分鐘後過期
Else
Response.Write "您提交的信息頻率過快請過15分鐘後提交下一條"
Response.End
End If
%>
Now() 存完整日期時間<%
' ✅ 修正版:使用 Now()、統一時間窗、加入雜湊防竄改
Const LIMIT_MINUTES = 15
Const COOKIE_NAME = "post_limit"
Dim lastPost, nowTime, expiryTime
nowTime = Now()
lastPost = Request.Cookies(COOKIE_NAME)
If lastPost = "" Then
' 首次提交
Response.Cookies(COOKIE_NAME) = nowTime
Response.Cookies(COOKIE_NAME).Expires = DateAdd("n", LIMIT_MINUTES, nowTime)
' 可選:加入簡單簽名防竄改
' Response.Cookies(COOKIE_NAME) = nowTime & "|" & Hash(nowTime & "secret")
Else
' 檢查時間間隔
If DateDiff("n", CDate(lastPost), nowTime) < LIMIT_MINUTES Then
Response.Write "請間隔 " & LIMIT_MINUTES & " 分鐘後再提交"
Response.End
Else
' 更新時間戳
Response.Cookies(COOKIE_NAME) = nowTime
Response.Cookies(COOKIE_NAME).Expires = DateAdd("n", LIMIT_MINUTES, nowTime)
End If
End If
%>
<%
Const LIMIT_SECONDS = 60
If Session("last_post_time") = "" Then
Session("last_post_time") = Timer()
Else
If Timer() - Session("last_post_time") < LIMIT_SECONDS Then
Response.Write "請勿頻繁提交"
Response.End
End If
Session("last_post_time") = Timer()
End If
%>
<%
Function CheckPostLimit(userId, ipAddr)
Dim sql, rs, conn, nowTime, windowStart
nowTime = Now()
windowStart = DateAdd("n", -15, nowTime) ' 15 分鐘窗口
sql = "SELECT COUNT(*) FROM PostLog WHERE UserID = ? AND IPAddr = ? AND PostTime > ?"
Set rs = ExecuteQuery(sql, Array(userId, ipAddr, windowStart))
If Not rs.EOF And rs(0) > 5 Then ' 15 分鐘最多 5 篇
CheckPostLimit = False
Else
CheckPostLimit = True
' 記錄本次提交
ExecuteNonQuery "INSERT INTO PostLog (UserID, IPAddr, PostTime) VALUES (?, ?, ?)", Array(userId, ipAddr, nowTime)
End If
If IsObject(rs) Then rs.Close : Set rs = Nothing
End Function
%>
| 方案 | 安全性 | 複雜度 | 適用場景 |
|---|---|---|---|
| Cookie | 低(可繞過) | 低 | 匿名留言板、低風險表單 |
| Session | 中(Session 劫持風險) | 低 | 會員制系統、一般表單 |
| 資料庫+IP+User | 高 | 中 | 高風險操作、發文系統、API 限流 |
| Redis/記憶體快取 | 高 | 中高 | 高併發、分散式系統 |
<script>
document.querySelector('form').addEventListener('submit', function() {
var btn = this.querySelector('button[type=submit]');
btn.disabled = true;
btn.textContent = '提交中...';
// 可選:設定 10 秒後恢復按鈕,防止網路異常卡死
setTimeout(function() { btn.disabled = false; btn.textContent = '提交'; }, 10000);
});
</script>