如何阻止直接下载文件

3

我的网站上有一些下载内容。我希望只有已登录的用户才能访问并下载这些文件。

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

我在网上搜索了很久,但没有找到任何好的答案。请建议我应该如何做。


请查看http://stackoverflow.com/questions/13881041/htaccess-deny-acces-to-directory-if-logged-out-checked-with-php,了解如何使用php实现此功能。 - undefined
这不是直接的文件链接,而是一个重定向,如果用户没有登录则跳转到一个 PHP 文件。 - undefined
2个回答

8

在成员文件夹中创建新文件夹“files”,将所有歌曲移动到此处,创建新的 .htaccess 文件并添加以下行:

Order Deny,Allow
Deny from all

在文件夹“members”中创建文件“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


0

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

Order deny,allow
Deny from all

访问此目录中文件的服务器和脚本仍将正常工作,但通过 URL 直接访问将无法实现。


它不仅拒绝直接链接,也会拒绝用户点击下载链接。 - undefined
你的链接正在调用一个PHP脚本来处理下载,首先检查用户是否已登录? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接