简体   繁体   中英

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. 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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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