How to download an mp3 file from remote url?

后端 未结 3 1276
夕颜
夕颜 2021-01-24 11:10

I am redirecting my website to a url where only an mp3 file is streaming and I want that file to be downloaded to local computer. how can i do that?

I have already searc

3条回答
  •  深忆病人
    2021-01-24 11:49

    Use CURL to download, then you can use file_get_contents to save file on server, or you can use some headers to force download the file.

    $ch = curl_init('http://url-to-file.com/audio.mp3');
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_NOBODY, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
    $output = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($status == 200) {
        file_put_contents(dirname(__FILE__) . '/audio.mp3', $output);
    }
    

    Download to browser:

    $ch = curl_init('http://url-to-file.com/audio.mp3');
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_NOBODY, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
    $output = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($status == 200) {
        header("Content-type: application/octet-stream"); 
        header("Content-Disposition: attachment; filename=audio.mp3"); 
        echo $output;
        die();
    }
    

提交回复
热议问题