Search code examples
htmlbrowsermp3

prevent browser to play mp3 in new browser window


is there a way to prevent a browser from opening an mp3 in a new browser window?

i have a normal link to mp3 file like

 <a href="link_to_mp3">some.mp3</a>

and of course you can download it with right click -> save as. but some users don't know that. so if they click on a link, a new window opens where they can listen to that mp3.

issue is, i want the users to download the files once instead of listen to them thousand times over my server ;)


Solution

  • Through html only you cannot force the link to open a file save dialog.

    Instead you can achieve that through PHP and with some custom headers as seen here

    A simple download.php file could look like:

        <?php
         
         $file = $_GET['file'];
         $dir = "path/to/files/";
         
         if(!file)
         {
             die('file not found');
         }
         else
         {
             $local_file = $dir . $file['filename'];
             $file = fopen($local_file, "r");  
    
    
             header("Cache-Control: public");
             header('Content-Type: application/octet-stream'); 
             header("Content-Description: File Transfer");
             header("Content-Disposition: attachment; filename=$file");
             header("Content-Transfer-Encoding: binary");
            
             // set download rate
             $download_rate = 100.0;
             // fetch the file
             fread($file, round($download_rate * 1024)); 
             // close the file stream
             fclose($file);
         }
         ?>
    

    Where you can specify the directory where all your files as saved, as well as a download rate if needed to limit the speed at which the file can be downloaded.

    Update

    Forgot to mention that you will then change your links to:

     <a href="download.php?file=test.mp3">some.mp3</a>
    

    where test.mp3 will be changed to your particular download