Asaduzzaman Noor
Asaduzzaman Noor

Reputation: 199

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.

Upvotes: 3

Views: 12577

Answers (2)

Asaduzzaman Noor
Asaduzzaman Noor

Reputation: 199

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

Upvotes: 8

RigidBody
RigidBody

Reputation: 664

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.

Upvotes: 0

Related Questions