把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 这张“禁止盗链”的图片!函数