整改一些业务系统时,加了WEB资源文件权限,好比上传doc,可能随机命名,但总可能被猜到,猜到就能访问到。php
以Apache为例,在禁止访问文件目录(file_path)下新建 .htaccesshtml
# 单个文件 <Files ~ "\.jpg$">
# 多个文件(写着就不让访问了) <Files ~ "\.(jpg|png|pdf|rar|zip|doc|docx|xls|xlsx|ppt|pptx)$"> Order allow,deny Deny from all </Files>
若是是IIS .net,能够在“MIME类型”设置可访问的资源文件后缀名
这样一来,下面两种方式都没法打开:浏览器
一、app
http://localhost/images/qwert.jpg
二、post
<img src="images/qwert.jpg" />
file_id | file_url | file_user_id |
---|---|---|
qwert_ooo | qwert.jpg | user1 |
12345_ooo | 12345.jpg | user2 |
<?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; }
备注:url
1.Content-Disposition:.net
参数 | 做用 |
---|---|
inline | 用默认浏览器打开非图片文件(Edge等浏览器有效,而Chrome一概选择下载) |
attachment | 下载 |
2.上述代码,ob_start()和ob_clean()须要一块儿使用,或者都不要,不然没法输出任何文件,即便查看Header信息是正确的设计
官方文档:输出缓冲必须已被 ob_start() 以 PHP_OUTPUT_HANDLER_CLEANABLE 标记启动。不然 ob_clean() 不会有效果。
<!doctype html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <img src="fileread.php?file_id=qwert_ooo"/> </body> </html>
一、code
http://localhost/fileread.html
二、htm
http://localhost/fileread.php?file_id=qwert_ooo