Thursday, 6 October 2016

How to download audio file from any server in php

Download audio file from server using Curl

After so many efforts and time I have downloaded all the audio file from my server to local diectory.

Here is the code that I have written.I have a CSV file which contains all the links of the audio files

"http://www.dsdsdsdsd--/download/324324","2016-10-06"
"http:///www.dsdsdsdsd--/download/32qww4324","2016-10-06"

 .............................

...............................

Curl must me installed in your system.


First You need to parse this file to get the Url's then hit the URL using curl

<?php 

$file       = '/var/www/html/test/results.csv';
$fileData   = fopen($file,'r');
while($row = fgets($fileData)){ 

    $tempUrl         =  explode(",",$row);
    $tempFileNameArr = explode("/",$tempUrl[0]);
    //print_r($tempFileNameArr);
    $remoteFileName  = rtrim($tempFileNameArr[6],'"');
    
    $ch   = curl_init();
    echo $tempUrl[0];
    $url = trim($tempUrl[0],'"');
    $url = rtrim($url, '/\\');
    echo "FInal ULR::$url";
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    echo "Strlen is::".strlen(trim($tempUrl[0]));
    $fp = fopen($remoteFileName.'.mp3', 'w');

    // Set CURL to write to disk
    curl_setopt($ch, CURLOPT_FILE, $fp);

    // Execute download
    curl_exec ($ch);
    echo "status::".$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $output = '';
    if (curl_error($ch)){
        $output .= "\n". curl_error($ch);
    }
    echo $output;
    //echo "output".$output;
    curl_close ($ch);

    fclose($fp);

}
fclose($fileData);

?>



Problem faced:

1.Status 0 from curl request 

References:

1. https://curl.haxx.se/docs/manpage.html#-L

2.http://stackoverflow.com/questions/2392677/best-way-to-remove-trailing-slashes-in-urls-with-php


2. Status 301

Add this line will solve your problem


curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

http://stackoverflow.com/questions/21233771/php-curl-function-301-error


CURLOPT_FOLLOWLOCATION cannot be activated when 

in safe_mode or an open_basedir is set



Solution 1:

Set safe_mode = Off in your php.ini file (it's usually 
in /etc/ on the server). If that's already off, then look around for 
the open_basedir stuff in the php.ini file and comment that 
line (#open_basedir...). Restart apache server.