How to download an mp3 file from remote url?

后端 未结 3 1273
夕颜
夕颜 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:28

    There are two ways to do it. First way is use function readfile - it will be faster, then all other methods.

    function curl_get_file_size( $url ) {
        $result = -1;    
        $curl = curl_init( $url );    
        curl_setopt( $curl, CURLOPT_NOBODY, true );curl_setopt( $curl, CURLOPT_HEADER, true );curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
        $data = curl_exec( $curl );
        curl_close( $curl );
        if( $data ) {
            $content_length = "unknown";
            $status = "unknown";
            if( preg_match( "/^HTTP\/1\.[01] (\d\d\d)/", $data, $matches ) )  $status = (int)$matches[1];
            if( preg_match( "/Content-Length: (\d+)/", $data, $matches ) )   $content_length = (int)$matches[1];
            if( $status == 200 || ($status > 300 && $status <= 308) ) 
                $result = $content_length;
        }
        return $result;
    }
    
    function run() {
            global $url,$title;
            header("Content-type: audio/mpeg");
            header("Content-Disposition: attachment; filename=$title.mp3");
            header("Content-length: " . curl_get_file_size($url));
            header("accept-ranges: bytes");
            readfile($url);
        }
    run();
    

    Second way is when you download full file and then return it

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_NOBODY, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
    $output = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($status == 200) {
        header("Content-type: audio/mpeg");
        header("Content-Disposition: attachment; filename=$title.mp3");
        header("Content-length: " . strlen($output));
        header("accept-ranges: bytes");
        echo $output;
        die();
    }
    

提交回复
热议问题