A snippet that helps you download files from the web, with the use of the well known cURL library for php.
In this tutorial we will try to fetch a file from the web, using the cURL library.
As you may know the cURL library provides us with a fast and easy way to fetch content from the web, as in adition to the well known socket functions - which are used by the cURL library - cURL will also follow headers, send headers, and in general it will work more like a browser.
In this cURL tutorial, we've learned how to fetch content from a web page (eg. an RSS feed) and it can be also used to fetch files, but with a big impact in the memory, as this implementation will fetch the whole file to the memory and then we will be able to save it to the disk.
To prevent this, cURL has an embedded directive called CURLOPT_FILE which gets a file handler as a parameter, which is using for saving the file while it is downloaded. Here is how we use this directive :
curl_setopt($ch, CURLOPT_FILE, $fp);?>
where $fp is our file handler.
Here is a complete snippet which will download and save files for you. Take a look at the comments for some additional information :
<?php /* This is usefull when you are downloading big files, as it will prevent time out of the script : */ set_time_limit(0); ini_set('display_errors',true);//Just in case we get some errors, let us know....
$fp = fopen (dirname(__FILE__) . '/a.rss', 'w+');//This is the file where we save the information $ch = curl_init('http://www.webdigity.com/rss.php');//Here is the file we are downloading curl_setopt($ch, CURLOPT_TIMEOUT, 50); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_exec($ch); curl_close($ch); fclose($fp); ?>
That's all. After this script is finished, we should have a file called a.rss to the script's folder.