How to download images with cURL PHP

If you would like to download images from URL using PHP, use this snippet.

I've tried it with HTTPS and seems to work fine. I am no master of cURL but I've read you might encounter issues with SSL. Watch out for those in case the snippet doesn't work.

<?php 
function grab_image($url,$saveto){
  $ch = curl_init ($url);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
  $raw=curl_exec($ch);
  curl_close ($ch);
  if(file_exists($saveto)){
      unlink($saveto);
  }
  $fp = fopen($saveto,'x');
  fwrite($fp, $raw);
  fclose($fp);
}

for ($i=1; $i < 17; $i++) {
  grab_image("https://url-".$i.".jpg","image-".$i.".jpg");
}Code language: HTML, XML (xml)

Leave a Reply

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