PHP: How can I block direct URL access to a file, but still allow it to be downloaded by logged in users?

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_song.php and add the following code:

if( !empty( $_GET['name'] ) )
{
  // check if user is logged    
  if( is_logged() )
  {
    $song_name = preg_replace( '#[^-\w]#', '', $_GET['name'] );
    $song_file = "{$_SERVER['DOCUMENT_ROOT']}/members/files/{$song_name}.mp3";
    if( file_exists( $song_file ) )
    {
      header( 'Cache-Control: public' );
      header( 'Content-Description: File Transfer' );
      header( "Content-Disposition: attachment; filename={$song_file}" );
      header( 'Content-Type: application/mp3' );
      header( 'Content-Transfer-Encoding: binary' );
      readfile( $song_file );
      exit;
    }
  }
}
die( "ERROR: invalid song or you don't have permissions to download it." );

And now, you can use this URL to get the song file:
http://mysite.com/members/get_song.php?name=my-song-name

Leave a Comment