How to block direct download file

喜欢而已 提交于 2020-03-21 03:31:22

问题


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. Direct File Link: 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.


回答1:


Into folder members create new folder files, move here all your songs, create new .htaccess file and add the following lines:

Order Deny,Allow
Deny from all

Into folder members create file get_file.php and add the following code:

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




回答2:


Put the files you want to protect in a separate directory and add an .htaccess file with the following:

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.



来源:https://stackoverflow.com/questions/39550660/how-to-block-direct-download-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!