經典 ASP 的 <!-- #include file="..." --> 為**編譯期靜態包含**,無法根據變數動態決定引入檔案。若需根據條件載入不同檔案,需改用執行期讀取 + Execute 方案。
<%
Function IncludeFile(filename)
Dim fso, f, content, re, aspStart, aspEnd, plainText
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(Server.MapPath(filename), 1) ' 1=ForReading
content = f.ReadAll
f.Close
Set f = Nothing
Set fso = Nothing
' 解析 ASP 區塊 <% ... %> 並用 Execute 執行
Set re = New RegExp
re.Pattern = "<%\s*(.*?)\s*%>"
re.Global = True
re.MultiLine = True
aspEnd = 1
aspStart = InStr(aspEnd, content, "<%")
Do While aspStart > aspEnd
' 輸出純 HTML 部分
plainText = Mid(content, aspEnd, aspStart - aspEnd)
If plainText <> "" Then Response.Write plainText
' 找尋結束 %>
aspEnd = InStr(aspStart, content, "%>")
If aspEnd = 0 Then Exit Do ' 未閉合
' 擷取 ASP 程式碼並執行
Dim aspCode
aspCode = Mid(content, aspStart + 2, aspEnd - aspStart - 2)
Execute aspCode
aspEnd = aspEnd + 2
aspStart = InStr(aspEnd, content, "<%")
Loop
' 輸出剩餘 HTML
If aspEnd <= Len(content) Then
Response.Write Mid(content, aspEnd)
End If
Set re = Nothing
End Function
%>
<%
Dim template
template = "header_" & Session("lang") & ".asp" ' 如 header_zh.asp, header_en.asp
Call IncludeFile(template)
%>
<div id="main">主要內容</div>
<%
Call IncludeFile("footer.asp")
%>
| 限制 | 影響 |
|---|---|
無法使用 Option Explicit | 動態 Execute 代碼無法強制變數宣告,易產生拼字錯誤。 |
| 變數作用域 | Execute 在當前 Procedure 執行,區域變數會洩漏/衝突。 |
| 效能 | 每次請求皆讀檔、解析、編譯,比靜態 Include 慢數倍。 |
| 除錯困難 | 錯誤行號指向呼叫處,而非實際被引入檔案的行號。 |
| 安全性 | 若 filename 來自用戶輸入,極高風險(任意檔案讀取/程式碼執行)。**嚴禁**直接帶入 Request 參數。 |
Function SafeInclude(userInput)
Dim allowedFiles, file
allowedFiles = Array("header.asp", "footer.asp", "sidebar.asp", "ads_top.asp")
' 嚴格白名單驗證
For Each file In allowedFiles
If StrComp(file, userInput, 1) = 0 Then
Call IncludeFile(file)
Exit Function
End If
Next
' 不在白名單:記錄攻擊嘗試、輸出錯誤或預設檔案
Response.Write ""
End Function
僅在**舊系統維護、無法重構、檔案名稱完全由伺服器端邏輯決定(無用戶輸入)**時使用動態 Include。新專案請採用 Server.Execute 或現代框架。