Home Backend Development PHP Tutorial PHP code for remotely grabbing website images and saving them

PHP code for remotely grabbing website images and saving them

Jul 25, 2016 am 09:12 AM

Example, PHP code to capture website data.

  1. /**
  2. * A class for grabbing images
  3. *
  4. * @package default
  5. * @author WuJunwei
  6. */
  7. class download_image
  8. {
  9. public $save_path; //The save address of the captured image
  10. //The size limit of the captured image (unit: Bytes) Only capture images larger than size than this limit
  11. public $img_size=0;
  12. //Define a static array to record the hyperlink addresses that have been crawled to avoid repeated crawling
  13. public static $ a_url_arr=array();
  14. /**
  15. * @param String $save_path The save address of the captured image
  16. * @param Int $img_size The save address of the captured image
  17. */
  18. public function __construct($save_path,$img_size)
  19. {
  20. $this->save_path=$save_path;
  21. $this->img_size=$img_size ;
  22. }
  23. /**
  24. * Method of recursively downloading and capturing images of the homepage and its subpages (recursive)
  25. *
  26. * @param String $capture_url URL used to capture images
  27. *
  28. */
  29. public function recursive_download_images($capture_url)
  30. {
  31. if (!in_array($capture_url,self::$a_url_arr)) //Not captured
  32. {
  33. self: :$a_url_arr[]=$capture_url; //Counted into static array
  34. } else //After capture, exit the function directly
  35. {
  36. return;
  37. }
  38. $this->download_current_page_images($capture_url); //Download All pictures on the current page
  39. //Use @ to block warning errors caused by the inability to read the capture address
  40. $content=@file_get_contents($capture_url);
  41. //Match the regular pattern before ? in the href attribute of the a tag
  42. $a_pattern = "|]+href=['" ]?([^ '"?]+)['" >]|U";
  43. preg_match_all($a_pattern, $content, $a_out, PREG_SET_ORDER);
  44. $tmp_arr=array(); //Define an array to store the hyperlink address of the image captured under the current loop
  45. foreach ($a_out as $k => $v)
  46. {
  47. /**
  48. * Remove empty '', '#', '/' and duplicate values ​​​​in hyperlinks
  49. * 1: The value of the hyperlink address cannot be equal to the url of the current crawled page, otherwise it will fall into an infinite loop
  50. * 2: Hyperlink is '' or '#', '/' is also this page, which will also fall into an infinite loop,
  51. * 3: Sometimes a hyperlink address will appear multiple times in a web page. If it is not removed, it will cause damage to a sub-page. for repeated downloads)
  52. */
  53. if ( $v[1] && !in_array($v[1],self::$a_url_arr) &&!in_array($v[1],array('#',' /',$capture_url) ) )
  54. {
  55. $tmp_arr[]=$v[1];
  56. }
  57. }
  58. foreach ($tmp_arr as $k => $v)
  59. {
  60. //Hyperlink path address
  61. if ( strpos($v, 'http://')!==false ) //If the url contains http://, you can access it directly
  62. {
  63. $a_url = $v;
  64. }else //Otherwise the proof is Relative address, the access address of the hyperlink needs to be reassembled
  65. {
  66. $domain_url = substr($capture_url, 0,strpos($capture_url, '/',8)+1);
  67. $a_url=$domain_url.$v;
  68. }
  69. $this->recursive_download_images($a_url);
  70. }
  71. }
  72. /**
  73. * Download all images under the current webpage
  74. *
  75. * @param String $capture_url The webpage address used to capture images
  76. * @return Array An array of the url addresses of the img tags of all images on the current webpage
  77. */
  78. public function download_current_page_images($capture_url)
  79. {
  80. $content=@file_get_contents($capture_url); / /Shield warning errors
  81. // Match the regular part before ? in the src attribute of the img tag
  82. $img_pattern = "|]+src=['" ]?([^ '"?]+) ['" > ;'.$capture_url . "Total found" . $photo_num . " pictures";
  83. foreach ($img_out as $k => $v)
  84. {
  85. $this->save_one_img($capture_url ,$v[1]);
  86. }
  87. }
  88. /**
  89. * Method to save a single image
  90. *
  91. * @param String $capture_url The webpage address used to capture the image
  92. * @param String $img_url The url of the image that needs to be saved
  93. *
  94. */
  95. public function save_one_img($capture_url,$img_url)
  96. {
  97. //Picture path address
  98. if ( strpos($img_url, 'http://')!==false )
  99. {
  100. // $img_url = $img_url;
  101. }else
  102. {
  103. $domain_url = substr($capture_url, 0,strpos($capture_url, '/',8)+1);
  104. $img_url=$domain_url.$img_url ;
  105. }
  106. $pathinfo = pathinfo($img_url); //Get the picture path information
  107. $pic_name=$pathinfo['basename']; //Get the name of the picture
  108. if (file_exists($this->save_path.$ pic_name)) //If the image exists, it proves that it has been captured, exit the function
  109. {
  110. echo $img_url . 'The image has been captured !
    ';
  111. return;
  112. }
  113. //Read the image content into a string
  114. $img_data = @file_get_contents($img_url); //Block because the image address cannot be read Get the warning error caused by
  115. if ( strlen($img_data) > $this->img_size ) //Download pictures whose size is larger than the limit
  116. {
  117. $img_size = file_put_contents($this->save_path . $pic_name, $ img_data);
  118. if ($img_size)
  119. {
  120. echo $img_url . 'Image saved successfully!
    ';
  121. } else
  122. {
  123. echo $img_url . 'Failed to save image!
    ';
  124. }
  125. } else
  126. {
  127. echo $img_url . 'Image reading failed!
    ';
  128. }
  129. }
  130. } // END
  131. set_time_limit(120); //Set the maximum execution time of the script according to the situation
  132. $download_img=new download_image('E:/images/',0); //Instantiate the download image object
  133. $download_img->recursive_download_images('http://bbs.it-home.org/'); //Recursive capture image method
  134. //$download_img->download_current_page_images($_POST['capture_url']); / /Method to only grab the current page pictures
  135. ?>
Copy code


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles