防盜鏈|防盜鏈
如果我們知道一個靜態檔案的實際路徑如:http://www.xx.com/download/51windows.pdf,如果伺服器沒有作特別的限制設定,我們就可以毫不費力的把它下載下來!當網站提供51windows.pdf下載時,怎麼樣才能讓下載者無法得到他的實際路徑呢!本文就來介紹如何使用Asp來隱藏檔案的實際下載路徑。
我們在管理網站檔案時,可以把副檔名一樣的檔案放在同一個目錄下,起一個比較特別名字,例如放pdf檔案目錄為the_pdf_file_s,把下面代碼另存新檔down.asp,他的網上路徑為http://www.xx.com/down.asp,我們就可以用http://www.xx.com/down.asp?FileName=51windows.pdf來下載這個檔案了,而且下載者無法看到這個檔案實際下載路徑的!在down.asp中我們還可以設定下載檔案是否需要登陸,判斷下載的來源頁是否為外部網站,從而可以做到防止檔案被盜鏈。
範例程式碼:
<%
From_url = Cstr(Request.ServerVariables("HTTP_REFERER"))
Serv_url = Cstr(Request.ServerVariables("SERVER_NAME"))
if mid(From_url,8,len(Serv_url)) <> Serv_url then
response.write "非法連結!" '防止盜鏈
response.end
end if
if Request.Cookies("Logined")="" then
response.redirect "/login.asp" '需要登陸!
end if
Function GetFileName(longname)'/folder1/folder2/file.asp=>file.asp
while instr(longname,"/")
longname = right(longname,len(longname)-1)
wend
GetFileName = longname
End Function
Dim Stream
Dim Contents
Dim FileName
Dim TrueFileName
Dim FileExt
Const adTypeBinary = 1
FileName = Request.QueryString("FileName")
if FileName = "" Then
Response.Write "無效檔案名稱!"
Response.End
End if
FileExt = Mid(FileName, InStrRev(FileName, ".") + 1)
Select Case UCase(FileExt)
Case "ASP", "ASA", "ASPX", "ASAX", "MDB"
Response.Write "非法操作!"
Response.End
End Select
Response.Clear
if lcase(right(FileName,3))="gif" or lcase(right(FileName,3))="jpg" or lcase(right(FileName,3))="png" then
Response.ContentType = "image/*" '對影像檔不出現下載對話方塊
else
Response.ContentType = "application/ms-download"
end if
Response.AddHeader "content-disposition", "attachment; filename=" & GetFileName(Request.QueryString("FileName"))
Set Stream = server.CreateObject("ADODB.Stream")
Stream.Type = adTypeBinary
Stream.Open
if lcase(right(FileName,3))="pdf" then '設定pdf類型檔案目錄
TrueFileName = "/the_pdf_file_s/"&FileName
end if
if lcase(right(FileName,3))="doc" then '設定DOC類型檔案目錄
TrueFileName = "/my_D_O_C_file/"&FileName
end if
if lcase(right(FileName,3))="gif" or lcase(right(FileName,3))="jpg" or lcase(right(FileName,3))="png" then
TrueFileName = "/all_images_/"&FileName '設定影像檔目錄
end if
Stream.LoadFromFile Server.MapPath(TrueFileName)
While Not Stream.EOS
Response.BinaryWrite Stream.Read(1024 * 64)
Wend
Stream.Close
Set Stream = Nothing
Response.Flush
Response.End
%>