Вариант № 1
Вместо того, чтобы собирать двоичные / необработанные данные в переменную и затем записывать, вы можете использовать опцию CURLOPT_FILE
, чтобы напрямую показать файл в curl для загрузки.
Вот функция:
// takes URL of image and Path for the image as parameter
function download_image1($image_url, $image_file){
$fp = fopen ($image_file, 'w+'); // open file handle
$ch = curl_init($image_url);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
curl_setopt($ch, CURLOPT_FILE, $fp); // output to file
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1000); // some large value to allow curl to run for a long time
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
// curl_setopt($ch, CURLOPT_VERBOSE, true); // Enable this line to see debug prints
curl_exec($ch);
curl_close($ch); // closing curl handle
fclose($fp); // closing file handle
}
А вот как это следует называть:
// test the download function
download_image1("http://www.gravatar.com/avatar/10773ae6687b55736e171c038b4228d2", "local_image1.jpg");
Вариант № 2
Теперь, Если вы хотите загрузить очень большой файл , эта функция, описанная выше, может не пригодиться. Вы можете использовать функцию ниже для обработки больших файлов. Кроме того, вы можете распечатать прогресс (в %
или в любом другом формате), если хотите. Приведенная ниже функция реализована с использованием функции callback
, которая записывает часть данных в файл в процессе загрузки.
// takes URL of image and Path for the image as parameter
function download_image2($image_url){
$ch = curl_init($image_url);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1000); // some large value to allow curl to run for a long time
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
curl_setopt($ch, CURLOPT_WRITEFUNCTION, "curl_callback");
// curl_setopt($ch, CURLOPT_VERBOSE, true); // Enable this line to see debug prints
curl_exec($ch);
curl_close($ch); // closing curl handle
}
/** callback function for curl */
function curl_callback($ch, $bytes){
global $fp;
$len = fwrite($fp, $bytes);
// if you want, you can use any progress printing here
return $len;
}
А вот как вызывать эту функцию:
// test the download function
$image_file = "local_image2.jpg";
$fp = fopen ($image_file, 'w+'); // open file handle
download_image2("http://www.gravatar.com/avatar/10773ae6687b55736e171c038b4228d2");
fclose($fp); // closing file handle