萬盛學電腦網

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

ASP 動態 Include 檔案:使用 FileSystemObject + Execute 實作執行期引入

問題背景

經典 ASP 的 <!-- #include file="..." --> 為**編譯期靜態包含**,無法根據變數動態決定引入檔案。若需根據條件載入不同檔案,需改用執行期讀取 + Execute 方案。

動態 Include 函數

<%
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

現代替代方案

  • Server.Execute / Server.Transfer:ASP 3.0+ 內建,可執行另一 ASP 頁面並回傳/轉移控制權,保有各自變數作用域。
  • 用戶端組合:AJAX 載入片段、前端模板引擎渲染。
  • 遷移至 ASP.NET Core Razor Pages:Partial View、ViewComponent、Tag Helper 完整支援動態組合。

結論

僅在**舊系統維護、無法重構、檔案名稱完全由伺服器端邏輯決定(無用戶輸入)**時使用動態 Include。新專案請採用 Server.Execute 或現代框架。

copyright © 萬盛學電腦網 all rights reserved