简体   繁体   English

如何阻止直接下载文件

[英]How to block direct download file

My website contains some download content. 我的网站包含一些下载内容。 I want to access download this file only for logged in user. 我只想访问已登录用户下载此文件。

If user type direct file url in browser it show forbidden page if user not logged in. Am not using any CMS. 如果用户在浏览器中键入直接文件url,则如果用户未登录则显示禁止页面。不使用任何CMS。 Direct File Link: localhost/files/questions/20160917070900-w2CdE9LZpE.zip 直接文件链接:localhost / files / questions / 20160917070900-w2CdE9LZpE.zip

I searched on net but failed to find any good answer. 我在网上搜索,但找不到任何好的答案。 Please suggest me how can I do it. 请建议我该怎么做。

Into folder members create new folder files, move here all your songs, create new .htaccess file and add the following lines: 放入文件夹成员中,创建新的文件夹文件,将所有歌曲移至此处,创建新的.htaccess文件,并添加以下行:

Order Deny,Allow
Deny from all

Into folder members create file get_file.php and add the following code: 放入文件夹成员中,创建文件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 to get the file: localhost/get_file.php?name=file_name 获取文件的URL:localhost / get_file.php?name = file_name

Put the files you want to protect in a separate directory and add an .htaccess file with the following: 将您要保护的文件放在单独的目录中,并添加具有以下内容的.htaccess文件:

Order deny,allow
Deny from all

The server and scripts that accesses files in this directory will still work but direct access by url will not. 访问该目录中文件的服务器和脚本仍然可以使用,但不能通过url直接访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM