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)

About Ricard Torres

Senior Front-end Software Engineer at Netcentric, from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast

Leave a Reply

Add <code> Some Code </code> if you need to.