28 May, 2010

Download file using curl

Following code sample is used to download file using curl. In this example we download image using curl and
save it to some file in our directory.

// URL to Download Image
$url = "http://www.someurl.com/images/image.jpg";
// Initialize a CURL session.
$ch = curl_init();
// Pass URL as parameter.
curl_setopt($ch, CURLOPT_URL, $url);
// Return contents.in a variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Data is in binary format
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
//open file in write mode
$file = fopen("somedir/somename.jpg", "w");
//filename that the transfered binary data is returned to
curl_setopt($ch, CURLOPT_FILE, $file);
//Grab the jpg and save the contents in the $data variable
$data = curl_exec($ch);
curl_close($ch); // close curl resource
?>

1 comment:

Drew said...

file_get_contents, done!