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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles