【问题标题】:How to block direct download file如何阻止直接下载文件
【发布时间】:2017-01-25 19:32:54
【问题描述】:

我的网站包含一些下载内容。我只想为登录用户访问下载此文件。

如果用户在浏览器中输入直接文件 url,如果用户未登录,则会显示禁止页面。我没有使用任何 CMS。 直接文件链接:localhost/files/questions/20160917070900-w2CdE9LZpE.zip

我在网上搜索但没有找到任何好的答案。请建议我该怎么做。

【问题讨论】:

标签: php .htaccess web


【解决方案1】:

进入文件夹成员创建新文件夹文件,将所有歌曲移至此处,创建新的 .htaccess 文件并添加以下行:

Order Deny,Allow
Deny from all

在文件夹成员中创建文件get_file.php并添加以下代码:

if( !empty( $_GET['name'] ) )
{
  // check if user is logged    
  if( is_logged() )
  {
    $file_name = preg_replace( '#[^-\w]#', '', $_GET['name'] );
  $question_file = "{$_SERVER['DOCUMENT_ROOT']}/files/questions/{$file_name}.zip";
  if( file_exists( $question_file ) )
  {
    header( 'Cache-Control: public' );
    header( 'Content-Description: File Transfer' );
    header( "Content-Disposition: attachment; filename={$question_file}" );
    header( 'Content-Type: application/zip' );
    header( 'Content-Transfer-Encoding: binary' );
    readfile( $question_file );
    exit;
   }
  }
}
die( "ERROR: invalid song or you don't have permissions to download it." );

获取文件的 URL:localhost/get_file.php?name=file_name

【讨论】:

    【解决方案2】:

    将您要保护的文件放在单独的目录中,并添加一个 .htaccess 文件,其中包含以下内容:

    Order deny,allow
    Deny from all
    

    访问此目录中文件的服务器和脚本仍然可以工作,但通过 url 直接访问则不行。

    【讨论】:

    • 它拒绝直接链接,但如果用户点击下载链接也会拒绝
    • 你的链接正在调用一个php脚本来处理下载,检查用户是否先登录?
    猜你喜欢
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 2020-06-01
    相关资源
    最近更新 更多