2014-09-12 81 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 

这种用法是保护您的文件夹和文件名,但它使用的数据库。