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 http://ePHP.info
}

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

$contents = getfile("http://ephp.info/feed")

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

Leave a Reply

Your email address will not be published. Required fields are marked *