Download Remote File Using CURL and PHP

Download Remote File Using CURL and PHP

Sometimes you need to download URL’s contents using the CURL library, included inside PHP (e.g if you want to use a web-based API, provided by service like TinyURL, Digg, Twitter). It’s actually very simple and faster to use than other methods of downloading remote file like the file(), file_get_contents() or fsockopen().

Also, CURL is very customizeable. You can POST data to the downloaded URL, simulate user-agent (browser) or other headers. The simplest version of a PHP function to retrieve file’s contents using PHP’s CURL is below:

function getfile($url) { $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); $downloaded = curl_exec($ch); curl_close($ch); return $downloaded; // More great PHP snippets at }

After you include the function in your file, you can simply call it like that:

$contents = getfile("")

And the $content variable will now have this blog’s RSS feed.