Allow Playing mp3 audio files but prevent download from a direct link with php and .htaccess

Allow Playing mp3 audio files but prevent download from a direct link with php and .htaccess

Jul 17,2021

Folder structure:

/audios

      index.php

      /mp3

           .htaccess

           sample.mp3

Step 1: add the following code to your index file

    

<?php

 $file = 'mp3/'.$_GET['file'];     

 if($file&&file_exists($file)){         

 header('Content-Description: File Transfer');         

 header('Content-Type: application/octet-stream');         

 header('Content-Transfer-Encoding: binary');         

 header('Expires: 0');         

 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

     header('Pragma: public');        

header('Content-Length: ' . filesize($file));        

ob_clean();         

 flush();         

 readfile($file);        

exit;     

}    

 else{         

 die();     

}

  

Step 2: Add the following code to your .htaccess file:

 

#This allows your php to only access this folder

 <FilesMatch "\.(mp3)$"> Order allow,deny Deny from all </FilesMatch>

 

 

Step 3: Finally change your audio source to look like this in the audio player

 

 <audio controls controlsList="nodownload">

 

 <source class="lazy" data-src="https://yourservice.com/audios/index.php?file=sample.mp3" type="audio/mpeg">

Your browser does not support the audio element.

 </audio>