0

I am accessing an HTML page using server-side PHP and the page has a link to listen to an audio. The HTML looks like this:

<a href="http://audio.somesite.com/audio?lang=es&amp;text=sometext">
<span class="audio-blue">&nbsp;</span>
</a>

While processing the document, I need my server-side script to retrieve the file being referenced in the a tag above, and then serve the file to the client for streaming. I just need to get a hang of how to do the first, i.e. saving the file on the server from the HTML. Taking cue from a bunch of other questions that seemed to resemble this one, I tried this:

file_put_contents("myfile.mp3", fopen("http://audio.somesite.com/audio?lang=es&amp;text=sometext", 'r'));

The above obviously failed. I am sure there's something very straightforward that's eluding me. Any hints?

TheLearner
  • 2,813
  • 5
  • 46
  • 94
  • 1
    f_p_c requires either a string or a stream resource. fopen returns a file pointer resource. They are **NOT** interchangeable. Plus, that's bad coding. if the fopen fails for any reason, it'll return boolean false, which you then blindly write out to disk. never EVER assume success with external resources. – Marc B Dec 14 '15 at 15:34
  • 1
    You will need the direct link to the file on said server. As @MarcB, you should probably include a catch in there. This may help out. http://stackoverflow.com/questions/3938534/download-file-to-server-from-url EDIT: this doesn't show you how to add a catch, just an example of file management in PHP. – chriz Dec 14 '15 at 15:35
  • Actually, that's the thread I got the hint to write the statement I did. My only question is how can there not be any way to access content that's already coming to my computer, lack of a direct link notwithstanding? YouTube doesn't give out any direct links to its videos either but that doesn't stop services like ClipConverter.cc from accessing and downloading those videos, does it? – TheLearner Dec 14 '15 at 16:58

1 Answers1

0

Step by step...

  1. Load and parse the HTML with a DOM parser.
  2. Query the DOM for the link you want, and extract the href attribute value.
  3. Output the appropriate Content-Type header, and any other headers you need.
  4. Use readfile() or similar to stream the response. Do not use file_get_contents() which will buffer the whole response before sending.
Brad
  • 159,648
  • 54
  • 349
  • 530