简体   繁体   中英

Download file to server using API (it triggers prompt)

I want to store some data retrieved using an API on my server. Specifically, these are .mp3 files of (free) learning tracks. I'm running into a problem though. The mp3 link returned from the request isn't to a straight .mp3 file, but rather makes an ADDITIONAL API call which normally would prompt you to download the mp3 file.

file_put_contents doesn't seem to like that. The mp3 file is empty.

Here's the code:

$id = $_POST['cid'];
$title = $_POST['title'];

if (!file_exists("tags/".$id."_".$title))
{
    mkdir("tags/".$id."_".$title);
}
else
echo "Dir already exists";

file_put_contents("tags/{$id}_{$title}/all.mp3", fopen($_POST['all'], 'r'));

And here is an example of the second API I mentioned earlier: http://www.barbershoptags.com/dbaction.php?action=DownloadFile&dbase=tags&id=31&fldname=AllParts

Is there some way to bypass this intermediate step? If there's no way to access the direct URL of the mp3, is there a way to redirect the file download prompt to my server?

Thank you in advance for your help!

EDIT

Here is the current snippet. I should be echoing something, correct?

$handle = fopen("http://www.barbershoptags.com/dbaction.php?action=DownloadFile&dbase=tags&id=31&fldname=AllParts", 'rb');
$contents = stream_get_contents($handle);
echo $contents;

Because this echos nothing.

SOLUTION

Ok, I guess file_get_contents is supposed to handle redirects just fine, but this wasn't happening. So I found this function: https://stackoverflow.com/a/4102293/2723783 to return the final redirect of the API. I plugged that URL into file_get_contents and volia!

You seem to be just opening the file handler and not getting the contents using fread() or another similar function:

http://www.php.net/manual/en/function.fread.php

$handle = fopen($_POST['all'], 'rb')
file_put_contents("tags/{$id}_{$title}/all.mp3", stream_get_contents($handle));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM