Download and save images from a page using cURL

cURL, and it’s PHP extension libcURL which allows to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, and user+password authentication.

Also, read:

In this tutorial, I’m going to show you some amazing things that you can do using PHP and cURL. Below is complete script to save all images from another server to your server. You just need to give your desired web page URL, and all images will be saved on your server.

 

<?php
function makeCurlCall($url){
$curl = curl_init();
$timeout = 5;
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,$timeout);
curl_setopt($curl,CURLOPT_USERAGENT,‘Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13’);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
function getImages($html) {
$matches = array();
$url_regex = ‘~http://somedomain.com/images/(.*?)\.jpg~i’;
preg_match_all($url_regex, $html, $matches);
foreach ($matches[1] as $img) {
saveImages($img);
}
}
function saveImages($name) {
$url = ‘http://somedomain.com/images/’.$name.‘.jpg’;
$data = makeCurlCall($url);
file_put_contents(‘photos/’.$name.‘.jpg’, $data);
}
$i = 1;
$l = 10;
while ($i < $l) {
$html = makeCurlCall(‘http://somedomain.com/id/’.$i.‘/’);
getImages($html);
$i += 1;
}
?>

You may also like:


Leave a Reply

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