Download files using Curl

Download remote files programatically using curl.
A simple and effective function to download files hosted on remote server. In the following function set the variable $dir to your directory in which you want to store downloaded files.

Example given below how to call this function. Just pass the url of the file to be downloaded and a filename. The file will be downloaded with this filename in the given directory.


  function download_file_curl($url,$name){ 
   set_time_limit(0);
   $dir="files/";
   $fp = fopen ($dir . $name, 'w+');
   $ch = curl_init($url);
   curl_setopt($ch, CURLOPT_TIMEOUT, 30);
   curl_setopt($ch, CURLOPT_FILE, $fp);
   curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
   $data = curl_exec($ch);
   curl_close($ch);
 
   fwrite($fp, $data);
   fclose($fp);
 }

Call this function as follows

$url="http://ia.media-imdb.com/images/M/MV5BMTk2NTI1MTU4N15BMl5BanBnXkFtZTcwODg0OTY0Nw@@._V1_SY317_CR0,0,214,317_.jpg";
$name="avengers.jpg";
download_file_curl($url,$name);

$url is the file to be downloaded.
The file will be named $name after downloading.
Download files using Curl Download files using Curl Reviewed by JS Pixels on February 27, 2013 Rating: 5

2 comments:

  1. image on your blog background is not reachable, which makes hard to read text.

    ReplyDelete
  2. There was a problem with the theme. I have updated it and its ok now.

    ReplyDelete

Altaf Web. Powered by Blogger.