Download remote file with cURL

Posted on March 12, 2013

cURL stands for “Client for URLs”. cURL is a library (libcurl) which allows PHP to communicate with other servers with different type of protocols.
With the cURL its easy to download remote file/s with the following PHP code example:

$remote_file_src = '\URL\Path\of\Remote\File\';
$destination = '\Directory\Path\File\Download\';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $remote_file_src);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

$file_contents = curl_exec($ch);

curl_close($ch);

if ( $f = @fopen($destination, 'wb') ) 
{
     fwrite($f, $file_contents);
}

fclose($f);