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
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();
}