PHP如何禁止圖片檔案的被盜鏈

來源:互聯網
上載者:User

1、假設充許連結圖片的主機網域名稱為:www.test.com

2、修改httpd.conf

 SetEnvIfNoCase Referer "^http://www.test.com/" local_ref=1
<FilesMatch ".(gif|jpg)">
Order Allow,Deny
Allow from env=local_ref
</FilesMatch> 
 
這個簡單的應用不光可以解決圖片盜鏈的問題,稍加修改還可以防止任意檔案盜鏈下載的問題。

使用以上的方法當從非指定的主機連結圖片時,圖片將無法顯示,如果希望顯示一張“禁止盜鏈”的圖片,我們可以用mod_rewrite 來實現。

首先在安裝 apache 時要加上 --enable-rewrite 參數載入 mod_rewrite 模組。

假設“禁止盜鏈”的圖片為abc.gif,我們在 httpd.conf 中可以這樣配置:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)?test.com /.*$ [NC]
RewriteRule .(gif|jpg)$ http://www.test.com/abc.gif [R,L] 
 
當主機的圖片被盜鏈時,只會看到 abc.gif 這張“禁止盜鏈”的圖片!

一段防盜連的PHP代碼

<?php
$ADMIN[defaulturl] = "http://www.163.com/404.htm";//盜鏈返回的地址
$okaysites = array("http://www.163.com/","http://163.com"); //白名單
$ADMIN[url_1] = "http://www.163.com/download/";//下載地點1
$ADMIN[url_2] = "";//下載地點2,以此類推
$reffer = $HTTP_REFERER;
if($reffer) {
$yes = 0;
while(list($domain, $subarray) = each($okaysites)) {
if (ereg($subarray,"$reffer")) {
$yes = 1;
}
}
$theu = "url"."_"."$site";
if ($ADMIN[$theu] AND $yes == 1) {
header("Location: $ADMIN[$theu]/$file");
} else {
header("Location: $ADMIN[defaulturl]");
}
} else {
header("Location: $ADMIN[defaulturl]");
}
?>

使用方法:將上述代碼儲存為dao4.php

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.