Example of PHP + Ajax remote image capture and download

Source: Internet
Author: User

First View Results


Implementation principle

Send request: Send the entered target URL and save path name to image.info asynchronously. php file, which contains an ImageCatch class, Note: Because one is to specify the target image capture, one is to specify a URL, such as the form of http://www.111cn.net, therefore, there is also a parameter used to determine whether to specify the target crawling or website crawling.

Receiving request: Receives Two sent parameters, including the target URL and storage path, instantiates the ImageCatch class, and transmits the address and storage path, use the file_get_contents function to read the content of the target address and assign the value to the variable $ content.

First, specify the implementation of image capturing: it is relatively simple to specify the image capturing method. You can directly use the file_get_contents function to read the image and then use file_put_contents to write it to a file to save it.

Implementation of image capturing at the specified URL

The method is a little different from the method for capturing the specified image address. Because jquery + ajax is used to capture images in the refreshing mode, a request is sent once. First, let's talk about what request is sent for the first time. Obviously, the first request is to get all the image addresses and total number of images on the target website. How can I get all the image addresses on the target website? The idea is the same as above, but the method is different;

Step 1: Use the file_get_contents function to read the target URL and assign a value to the content variable.

Step 2: use regular expressions to match the src attributes of all img tags and save them in an array. Then, the image address of the webpage has been obtained.

Step 3: use regular expressions to match the href attributes of link labels of all style sheet files and save them in an array $ arr1

Step 4: Use the file_get_contents function to read the obtained style table file, use the regular expression to match the url background image address in the css style, and save it in an array $ arr2, in this way, the css image is retrieved again.

Step 5: Combine $ arr1 and $ arr2 with the array_merge function into $ arr and use an array $ arr3 ('total' => count ($ arr )) obtain the total number of images and append them to the array $ arr so that the image address and total number are obtained.

Step 6: Use json_encode to compile a json data returned Step 7: receive the returned json data and store the data in an array to determine whether the array is empty or not, then, call a function using the recursive method of the function. After each call, the first element of the array is removed from the returned result and the array is null or not, then, send the capture request until the array is empty and all the images have been crawled.

Now let's look at the example.

Index. php

The code is as follows: Copy code
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = utf-8"/>
<Title> PHP remote image capturing </title>
<Style>
Body {margin: 0; padding: 0 ;}
# Content {width: 90%; height: auto; margin: 0 auto; margin-top: 20px; font-size: 12px; color: #333 ;}
# Content. h1 {width: 100%; line-height: 30px; text-align: left ;}
# Content. h2 {width: 100%; line-height: 30px; text-align: left ;}
# Content. Schedule {width: auto; height: 12px; margin: 15px 0px; display: none; background: url ()}
# Content ul {width: 100%; height: auto; margin-top: 10px ;}
# Content ul li {height: 24px; line-height: 24px ;}
# Content font {color: # f00 ;}
</Style>
<Script type = "text/javascript" src = "js/jquery. js"> </script>
<Script>
$ (Document). ready (function (){
Var TargetUrl;
Var Save;
Function error (info ){
$ ('# Content. h2 font'). text (info );
 }
Function statusInfo (info ){
$ ('# Content ul'). append ('<li>' + info + '</li> ');
 }
// Disable the button
Function start_d (){
$ ('# Single, # more'). attr ('disabled ', 'disabled ');
 }
// Release button
Function start_s (){
$ ('# Single, # more'). removeProp ('disabled ');
 }
// Progress jump
Function href (){
Location. href = '# bottom ';
 }
// Capture a single image
$ ('# Content. h1 # Single'). click (function (){
TargetUrl = $ ('# content. h2. Targeturl'). val ();
Save = $ ('# content. h2. Save'). val ();
If (TargetUrl = ''){
Error ('* enter the target URL ');
Return;
  }
If (Save = ''){
Error ('* enter the save Directory ');
Return;
  }
Var zurl = new Array (TargetUrl );
Start_d ();
Crawl (zurl, Save );
});
Function Crawl (zurl, Save ){
Start_d ();
$ ('# Content. Schedule'). show ();
If (zurl. length> 0 ){
Var curl = zurl [0];
$. Ajax ({
Url: 'image. info. php? Single = Single ',
DataType: 'json ',
Type: 'post ',
Data: 'targeturl = '+ curl +' & Save = '+ Save,
Success: function (data ){
If (data. status = 'OK '){
StatusInfo ('remote image <font> '+ curl +' </font> capture succeeded and saved in <font> '+ data. fileSave + '</font> File size: <font>' + data. fileSize + '</font> ');
Zurl. shift (); // delete the first array element and return
Crawl (zurl, Save); // use function recursion
Href ();
} Else {
Zurl. shift (); // delete the first array element and return
Crawl (zurl, Save); // use function recursion
StatusInfo (data. status); // Display failure information
$ ('# Content. Schedule'). hide (); // hide the LOADING image
Start_s (); // The button is enabled.
Href ();
    }
   }
});
} Else {
$ ('# Content. Schedule'). hide ();
StatusInfo ('image capturing completed ');
Start_s ();
Href ();
  }
 }
// Capture multiple images
$ ('# Content. h1 # more'). click (function (){
TargetUrl = $ ('# content. h2. Targeturl'). val ();
Save = $ ('# content. h2. Save'). val ();
If (TargetUrl = ''){
Error ('* enter the target URL ');
Return;
  }
Var str =/^ (https? ://)? ([Da-z.-] +). ([a-z.] {2, 6}) ([/w.-] *) */? $ /;
If (! Str. test (TargetUrl )){
Error ('* incorrect target URL ');
Return;
  }
If (Save = ''){
Error ('* enter the save Directory ');
Return;
  }
Start_d ();
$ ('# Content. Schedule'). show ();
$. Ajax ({
Url: 'image. info. php? More = more ',
DataType: 'json ',
Type: 'post ',
Data: 'targeturl = '+ TargetUrl +' & Save = '+ Save,
Success: function (data ){
If (data [0]! = 'No '){
StatusInfo ('find the <font> '+ TargetUrl +' </font> <font> '+ data ['total'] +' </font> image on the target URL, capturing .... ');
Var zurl = new Array ();
For (I = 0; I <data ['total']; I ++ ){
Zurl. push (data [I]);
     }
Crawl (zurl, Save );
} Else {
StatusInfo ("no images found ");
$ ('# Content. Schedule'). hide ();
Start_s ();
    }
   }
});
});
$ ('# Clear'). click (function (){
$ ('# Content ul li'). remove ();
});
});
</Script>
</Head>
<Body>
<Div id = "content">
<H1> PHP remote image capturing program
<Div class = "h1">
Specify the image capture: <input type = "button" value = "start to capture" id = "Single"/> <font> target URL such as: http://www.111cn.Net/123.jpg </font> specify the URL capture: <input type = "button" value = "start to capture" id = "more"/> <font> target URL, for example: http://www.111cn.Net </font> <input type = "button" value = "clear status information" id = "clear"/>
</Div>
<Div class = "Schedule"> <font> capturing. Please wait... </font> </div>
<Div class = "h2"> target URL: <input type = "text" class = "TargetUrl" size = "40"/> save address: <input type = "text" class = "Save"/> <font> </div>
<Ul>
</Ul>
<A name = "bottom"> </a>
</Div>
</Body>
</Html>

Images.info. php

The code is as follows: Copy code

<? Php
Header ('content-Type; text/json; charset = utf-8 ');
$ Single = $ _ GET ['single '];
$ More = $ _ GET ['more'];
$ TargetUrl = $ _ POST ['targeturl'];
$ Save = $ _ POST ['save'];
// Determine whether to capture a single image or multiple images
If ($ Single = 'Singles '){
$ ImageCatch = new ImageCatch ($ TargetUrl, $ Save );
$ ImageCatch-> S ();
} Else if ($ more = 'more '){
$ ImageCatch = new ImageCatch ($ TargetUrl, $ Save );
$ ImageCatch-> M ();
}
// Image capturing
Class ImageCatch {
Private $ TargetUrl; // target address
Private $ Save; // Save address
Private $ FileName; // file name and path
Private $ Type; // file Type
Private $ Size; // file Size
// Constructor
Public function _ construct ($ TargetUrl, $ Save ){
$ This-> TargetUrl = str_replace ("'", '', $ TargetUrl); // remove single quotes
$ This-> Save = $ Save;
 }
// How to capture images in the CSS style sheet
Public function CSS (){
$ Content = @ file_get_contents ($ this-> TargetUrl );
// CSS image filtering
Preg_match_all ('/<link. + href = "? (.*?. Css )"?. +>/I ', $ content, $ css );
$ Css [1] = array_unique ($ css [1]); // remove duplicate values
$ Match2 = array ();
If (count ($ css [1])> 0 ){
Foreach ($ css [1] as $ val ){
If (! Preg_match ('/^ (https? : //)/I ', $ val )){
$ Val = $ this-> TargetUrl. '/'. $ val;
$ Csscontent = @ file_get_contents ($ val );
} Else {
$ Csscontent = @ file_get_contents ($ val );
    }
// Match the image URL
Preg_match_all ('/url (. *)/I', $ csscontent, $ cssimg );
$ Cssimg [1] = array_unique ($ cssimg [1]); // remove duplicate values
   }   
Foreach ($ cssimg [1] as $ val ){
// Remove ") characters
$ Val = preg_replace (array ('/"|)/'),'', $ val );
// Remove the ../character
$ Val = str_replace ('../', '', $ val );
// Check whether it starts with http: //. If not, add the URL to be crawled.
If (! Preg_match ('/^ (https? : //)/I ', $ val )){
Array_push ($ match2, $ this-> TargetUrl. '/'. $ val );
} Else {
Array_push ($ match2, $ val );
    }
   }
Return $ match2;
  }
 }
// Calculate and return the image quantity and address
Public function M (){
$ Content = @ file_get_contents ($ this-> TargetUrl );
// Webpage image filtering
$ Str = '//I ';
Preg_match_all ($ str, $ content, $ res );
If ($ res [1]) {
$ Res [1] = array_unique ($ res [1]); // remove duplicate values
$ Httpstr = '/^ (https? : //)/I ';
$ Match = array ();
Foreach ($ res [1] as $ val ){
If (! Preg_match ($ httpstr, $ val )){
Array_push ($ match, $ this-> TargetUrl. '/'. $ val );
} Else {
Array_push ($ match, $ val );
    }
   }
$ Cssimg = $ this-> CSS ();
// The total number of scanned css file images and the total number of webpage images
$ Total = array ("total" => count ($ match) + count ($ cssimg ));
$ Result = array_merge ($ total, $ match, $ cssimg );
// Return JSON data
Echo json_encode ($ result );
} Else {
$ Res = array ('no ');
Echo json_encode ($ res );
  }
Exit;
 }
// Capture and save the image
Public function S (){
$ This-> Type = substr (strrchr ($ this-> TargetUrl, '.'), 1 );
$ This-> FileName = $ this-> Save. '/'. substr (strrchr ($ this-> TargetUrl, '/'), 1 );
$ This-> imageType ();
$ Content = @ file_get_contents ($ this-> TargetUrl );
$ This-> imageDir ();
If (! @ File_put_contents ($ this-> FileName, $ content, FILE_USE_INCLUDE_PATH )){
@ Unlink ($ this-> FileName );
Exit ('{"status": "Not found'. $ this-> TargetUrl. 'image "}');
} Else {
$ This-> imageSize ();
Exit ('{"status": "OK", "FileSave ":"'. $ this-> FileName. '"," FileSize ":"'. $ this-> Size. '"}');
  }
 }
// Create a directory
Private function imageDir (){
If (! @ File_exists ($ this-> Save )){
If (! @ Mkdir ($ this-> Save, 0700 )){
Exit ('{"status": "failed to create and save the directory "}');
   }
  }
 }
// File type determination
Private function imageType (){
$ TypeArr = array ('jpg ', 'PNG', 'GIF', 'Zip', 'rar ');
If (! In_array ($ this-> Type, $ typeArr )){
Exit ('{"status": "The file extension to be crawled has an error,'. $ this-> TargetUrl .'"}');
  }
 }
// File size check
Private function imageSize (){
If (file_exists ($ this-> FileName )){
$ This-> Size = filesize ($ this-> FileName );
If ($ this-> Size> 1024*1024*1024 ){
$ This-> Size = round ($ this-> Size/1024/1024/, 2). 'GB ';
} Else if ($ this-> Size> 1024*1024 ){
$ This-> Size = round ($ this-> Size/1024/1024, 2). 'MB ';
} Else if ($ this-& gt; Size> 1024 ){
$ This-> Size = $ this-> Size/1024;
$ This-> Size = ceil ($ this-> Size). 'KB ';
} Else {
$ This-> Size = $ this-> Size. 'Bit ';
   }
} Else {
Return 'file not found ';
  }
 }
}
?>

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.