關於Web資源文件權限的簡單設置

整改一些業務系統時,加了WEB資源文件權限,好比上傳doc,可能隨機命名,但總可能被猜到,猜到就能訪問到。php

首先,禁止Url文件名直接訪問

以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

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;
}

備註:url

1.Content-Disposition:.net

參數 做用
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>

訪問方式

一、code

http://localhost/fileread.html

二、htm

http://localhost/fileread.php?file_id=qwert_ooo
相關文章
相關標籤/搜索