PHP如何禁止圖片文件的被盜鏈
1、假設充許連結圖片的主機域名為:www.test.com
2、修改httpd.conf
SetEnvIfNoCase Referer '^http://www.test.com/' local_ref=1<FilesMatch '.(gif|jpg)'>Order Allow,DenyAllow from env=local_ref</FilesMatch> 這個簡單的應用不光可以解決圖片盜鏈的問題,稍加修改還可以防止任意文件盜鏈下載的問題。
使用以上的方法當從非指定的主機連結圖片時,圖片將無法顯示,如果希望顯示一張“禁止盜鏈”的圖片,我們可以用mod_rewrite 來實現。
首先在安裝 apache 時要加上 --enable-rewrite 參數加載 mod_rewrite 模組。
假設“禁止盜鏈”的圖片為abc.gif,我們在 httpd.conf 中可以這樣配置:
RewriteEngine onRewriteCond %{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
