Force Download MP3 with PHP

2020-08-01 06:45发布

问题:

Be honest : I found the way to donwload mp3 files from s******d but Im not able to donwload the MP3 directly all the music is streaming in the browser.

I already try with someting like this

<a href="direct_download.php?file=fineline.mp3">Download the mp3</a>

but my donwload link is not .mp3, this is my line of code to donwload a file

href="<?php echo $val['stream_url']?>?client_id=67739332564a7130c3a05f90f2d02d2e">Descargar</a>.

When I use the the option

direct_download.php?file=

just donwload one file with the name

client_id=05b4f2000dad27aa9fc48d08915d7830.html

The complete php code that I use is

<?php
$file = $_GET['file'];
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file.";");
header("Content-Length: ".filesize($file));
readfile($file);
exit;
?>

Which can be accessed in any anchor like this:

<a href="direct_download.php?file=fineline.mp3">Download the mp3</a>

Could you please help me, or if you have a better ide, thank you guys

回答1:

if you are using html5 you can use download option

<a href="url_to_your_file.mp3" download>Download the mp3</a>

otherwise, you can use javascript

function saveAs(url) {    
  var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
  var xhr = new XMLHttpRequest();
  xhr.responseType = 'blob';
  xhr.onload = function() {
    var a = document.createElement('a');
    a.href = window.URL.createObjectURL(xhr.response);
    a.download = filename; 
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();
    delete a;
  };
  xhr.open('GET', url);
  xhr.send();
}

Call it from your link

<a href="javascript:" onclick="saveAs(url_to_your_file.mp3)">Download the mp3</a>


标签: php download mp3