2014-09-12 38 views
0

我有一個網站,您可以從中下載資源。從htaccess禁用文件夾公共訪問

我想要的是禁用存儲項目的文件夾的公共訪問權限,但允許他們通過網站訪問下載。

我在.htaccess中使用Order deny,allow,但是如果我使用它,我無法從網站下載。

它會給我錯誤404,試圖輸入文件的直接url。下載被執行。

我有以下代碼:

 $link = $item->link; 

     $link_headers = get_headers($link); 

     //Headers 
     if(isset($link_headers[0])) 
     { 
      header($link_headers[0]); 

     }//if exists 
     if(isset($link_headers[1])) 
     { 
      header($link_headers[1]); 

     }//if exists 
     if(isset($link_headers[2])) 
     { 
      header($link_headers[2]); 

     }//if exists 
     if(isset($link_headers[3])) 
     { 
      header($link_headers[3]); 

     }//if exists 
     if(isset($link_headers[4])) 
     { 
      header($link_headers[4]); 

     }//if exists 
     if(isset($link_headers[5])) 
     { 
      header($link_headers[5]); 

     }//if exists 
     if(isset($link_headers[6])) 
     { 
      header($link_headers[6]); 

     }//if exists 
     if(isset($link_headers[7])) 
     { 
      header($link_headers[7]); 

     }//if exists 
     if(isset($link_headers[8])) 
     { 
      header($link_headers[8]); 

     }//if exists 

     readfile($link); 

     exit; 

事情是,如果我把帶的.htaccess拒絕所有進入持有的所有項目進行下載,然後下載,因爲我沒有權限將不再工作的文件夾我希望只有那些試圖從url直接鏈接到文件的人才能使用它。

+0

你想密碼保護文件夾嗎?你在尋找某種用戶級訪問限制嗎? – cmorrissey 2014-09-12 14:35:49

+0

我想要的是不允許從直接鏈接訪問文件。例如像這樣訪問www.website.com/downloads/file32.jpg應該返回權限被拒絕。 – 2014-09-12 14:37:52

+0

您必須使用文件的路徑。我想你使用你的文件的鏈接。 – hkulekci 2014-09-12 15:23:15

回答

0

實現此目的的一種方法是通過檢查http-referrer的腳本進行下載。頭當然可以手動修改,但我覺得做的事情比這更復雜的將是一個矯枉過正:

/* 
Change your download links to point to a php script, or use .htaccess to rewrite downloads to the same file 
*/ 
<a href="download.php?file=somefile.zip">Download</a> 

//download.php 

if ($_SERVER['HTTP_REFERER'] == "your_downloads_page.html") { 
    $file = $_GET['file']; 
    if (file_exists($file)) { 
     header('Content-Description: File Transfer'); 
     header('Content-Type: application/octet-stream'); 
     header('Content-Disposition: attachment; filename='.basename($file)); 
     header('Expires: 0'); 
     header('Cache-Control: must-revalidate'); 
     header('Pragma: public'); 
     header('Content-Length: ' . filesize($file)); 
     readfile($file); 
     exit; 
    } 
} 

然而一定要添加一些安全檢查,使用戶無法下載文件,他們不應該不能被允許。也許過濾所有斜線和雙點。

0

如果你保護你的文件和文件路徑,你可以使用download.php文件。

的download.php文件內容

<?php 
// Connect to db and get file information from db. 
// $db_filename and $db_filetype getting from db 

header("Content-disposition: attachment; filename=def.file_type"); // def.pdf 
header("Content-type: " . $db_filetype); // application/pdf 
readfile("/path/of/your/files/".$db_filename); // /project/home/downloads/abc.pdf 

用法:

download.php?file_id=1 

這種用法是保護您的文件夾和文件名,但它使用的數據庫。