How to Download and save images from a page using cURL

Sep 21, 2013, by admin

cURL, and its PHP extension libcURL which allows you 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.

In this article, 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.

 

  1. <?php
  2. function makeCurlCall($url){
  3. $curl = curl_init();
  4. $timeout = 5;
  5. curl_setopt($curl,CURLOPT_URL,$url);
  6. curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
  7. curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,$timeout);
  8. 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′);
  9. $output = curl_exec($curl);
  10. curl_close($curl);
  11. return$output;
  12. }
  13. function getImages($html) {
  14. $matches = array();
  15. $url_regex = ‘~http://somedomain.com/images/(.*?).jpg~i’;
  16. preg_match_all($url_regex, $html, $matches);
  17. foreach ($matches[1] as$img) {
  18. saveImages($img);
  19. }
  20. }
  21. function saveImages($name) {
  22. $url = ‘http://somedomain.com/images/’.$name.‘.jpg’;
  23. $data = makeCurlCall($url);
  24. file_put_contents(‘photos/’.$name.‘.jpg’, $data);
  25. }
  26. $i = 1;
  27. $l = 10;
  28. while ($i < $l) {
  29. $html = makeCurlCall(‘http://somedomain.com/id/’.$i.‘/’);
  30. getImages($html);
  31. $i += 1;
  32. }
  33. ?>

Hope this might be useful for you to get more updates like the page Bugtreat Technologies and to get updates of Templates like the page Cs Cart templates

Thanks to phpzag