0

I am trying to download audio file over php. I have tried download it with curl and wget. here are examples:

<?php
  exec('wget http://static1.grsites.com/archive/sounds/cartoon/cartoon001.wav');
?>

How can I download it by using one of two mentioned methods.

newdev
  • 79
  • 1
  • 9

1 Answers1

1

I think this should work for you:

<?php
    $url = 'http://static1.grsites.com/archive/sounds/cartoon/cartoon001.wav';
    header('Content-Type: audio/wav');
    header('Content-Disposition: inline;filename="name.wav"');
    header('Content-length: '.get_headers($url,1)['Content-Length']);
    header('Cache-Control: no-cache');
    header("Content-Transfer-Encoding: chunked");
    readfile("http://static1.grsites.com/archive/sounds/cartoon/cartoon001.wav");
?>
hanshenrik
  • 19,904
  • 4
  • 43
  • 89
David
  • 1,636
  • 19
  • 27
  • downloading it is just the first line. all the other lines are just serving it. also, this is a bad, very slow and memory-hungry approach, first before starting to serve the page, you download the entire file, and store the entire file in memory at once, before serving it. a much faster, and less memory hungry approach, would be to use readfile() instead of file_get_contents() - then the page would start getting served after the first couple of bytes have been downloaded, and just small parts of the file are kept in ram on the server at any given time – hanshenrik Apr 14 '18 at 17:54
  • if you remove `$audio = file_get_contents('http://static1.grsites.com/archive/sounds/cartoon/cartoon001.wav');`, and replace `echo $audio;` with `readfile("http://static1.grsites.com/archive/sounds/cartoon/cartoon001.wav");`, the page will load much faster, and use significantly less ram, than the file_get_contents approach, also it will use the same amount of ram, no matter how big the target file is. while the file_get_contents code use more ram depending on how big the music file is. is the music file 100MB? file_get_contents will use 100MB ram, readfile() will use a few kilobytes of ram. – hanshenrik Apr 14 '18 at 17:55
  • @hanshenrik You can't set the Content-length header then. The client won't know the size of the data and will usually show "unknown time remaining". – David Apr 14 '18 at 18:02
  • @psrcek `header('Content-length: '.get_headers($url)['Content-Length']);` – hanshenrik Apr 14 '18 at 18:03