把images目錄設置成不充許http訪問(把圖片目錄的:讀取、目錄瀏覽 兩個權限去掉)。
用一個PHP文件,直接用file函數讀取這個圖片。在這個PHP文件裏進行權限控制。
apache環境中,在你的圖片目錄中加上下面這個文件便可。php
文件名 .htaccess
文件內容以下html
# options the .htaccess files in directories can override.
# Edit apache/conf/httpd.conf to AllowOverride in .htaccess
# AllowOverride AuthConfig
# Stop the directory list from being shown
Options -Indexes
# Controls who can get stuff from this server.
Order Deny,Allow
Deny from all
Allow from localhost
其餘web環境如iss,nginx也相似。nginx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
class
imgdata{
public
$imgsrc
;
public
$imgdata
;
public
$imgform
;
public
function
getdir(
$source
){
$this
->imgsrc =
$source
;
}
public
function
img2data(){
$this
->_imgfrom(
$this
->imgsrc);
return
$this
->imgdata=
fread
(
fopen
(
$this
->imgsrc,
'rb'
),
filesize
(
$this
->imgsrc));
}
public
function
data2img(){
header(「content-type:
$this
->imgform」);
echo
$this
->imgdata;
//echo $this->imgform;
//imagecreatefromstring($this->imgdata);
}
public
function
_imgfrom(
$imgsrc
){
$info
=
getimagesize
(
$imgsrc
);
//var_dump($info);
return
$this
->imgform =
$info
[
'mime'
];
}
}
$n
=
new
imgdata;
$n
-> getdir(「1.jpg」);
//圖片路徑,通常存儲在數據庫裏,用戶沒法獲取真實路徑,可根據圖片ID來獲取
$n
-> img2data();
$n
-> data2img();
|
這段代碼是讀取圖片,而後直接輸出給瀏覽器,在讀取和輸出以前,進行用戶權限判斷。
這裏說的PHP讀取圖片,不是指讀取路徑,而是指讀取圖片的內容,而後經過
Header();輸入圖片類型,好比 gif png jpg等,下面輸出圖片的內容,因此用到了fread()
實際上,你看到 image.php?id=100 就是顯示這張圖片在瀏覽器上,而你查看源文件,看到的不會是圖片的路徑,而是亂碼似的圖片內容。
===========================================
相似於qq空間的加密相冊,只有輸入密碼才能訪問,而且直接在瀏覽器輸入 加密相冊中的相片地址也是沒法訪問。我目前的想法是 圖片的地址是一個php文件,經過 php 驗證權限 ,讀取圖片,並輸出,不知道除了這樣的方法還有更簡單高效的作法沒有?好比生成臨時的瀏覽地址,使用一些 nginx 的一些防盜鏈插件?
你能夠利用ngx_http_auth_basic_module來完成。web
修改配置文件數據庫
location / {
root /usr/local/nginx/html;
auth_basic 「Auth」;
auth_basic_user_file /usr/local/nginx/conf/htpasswd;
index index.php index.htm;
}
auth_basic 「Auth」中的Auth是彈出框(輸入用戶名和密碼)的標題
auth_basic_user_file /usr/local/nginx/conf/htpasswd; 中的/usr/local/nginx/conf/htpasswd是保存密碼的文件apache
PHP禁止圖片盜鏈
一、假設充許連結圖片的主機域名爲:www.test.com
二、修改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 中能夠這樣配置:ide
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 這張「禁止盜鏈」的圖片!函數