3

整改一些业务系统时,加了WEB资源文件权限,比如上传doc,可能随机命名,但总可能被猜到,猜到就能访问到。

首先,禁止Url文件名直接访问

以Apache为例,在禁止访问文件目录(file_path)下新建 .htaccess

# 单个文件
<Files ~ "\.jpg$">
# 多个文件(写着就不让访问了)
<Files ~ "\.(jpg|png|pdf|rar|zip|doc|docx|xls|xlsx|ppt|pptx)$">
   Order allow,deny
   Deny from all
</Files>
如果是IIS .net,可以在“MIME类型”设置可访问的资源文件后缀名

这样一来,下面两种方式都无法打开:

1、

http://localhost/images/qwert.jpg

2、

<img src="images/qwert.jpg" />

第二步,输出文件

假设数据表是这样设计的

file_id file_url file_user_id
qwert_ooo qwert.jpg user1
12345_ooo 12345.jpg user2

fileread.php 读取文件

<?php

$file_id = $_GET["file_id"]; // 得到网址中的文件id
// 根据$file_id,查找到文件的真实路径,比如 images/qwert.jpg;这里可以进一步做权限验证,比如是否属于用户user1
$file_url = "images/qwert.jpg"; 

if (file_exists($file_url)) {
    ob_start();
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file_url));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file_url));
    ob_clean();
    flush();
    readfile($file_url);
    exit;
}

备注:

1.Content-Disposition:

参数 作用
inline 用默认浏览器打开非图片文件(Edge等浏览器有效,而Chrome一律选择下载)
attachment 下载

2.上述代码,ob_start()和ob_clean()需要一起使用,或者都不要,否则无法输出任何文件,即使查看Header信息是正确的

官方文档:输出缓冲必须已被 ob_start() 以 PHP_OUTPUT_HANDLER_CLEANABLE 标记启动。否则 ob_clean() 不会有效果。

fileread.html 输出文件

<!doctype html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <img src="fileread.php?file_id=qwert_ooo"/>
</body>
</html>

访问方式

1、

http://localhost/fileread.html

2、

http://localhost/fileread.php?file_id=qwert_ooo

了小黄鱼
200 声望2 粉丝

技术小白