search
HomeBackend DevelopmentPHP TutorialDetailed tutorial on remote image collection with PHP_PHP tutorial

When we need to collect the content of a certain web page on the Internet, if the pictures on the target website are protected from hotlinking, the pictures we collect directly will not be available on our own website. Then we use a program to download the pictures on the target website to our website server, and then the pictures can be called.

This article will use PHP to implement the remote image collection function. Basic process:
1. Obtain the image address of the target website.
2. Read the image content.
3. Create a path to save the image and name the image.
4. Write the picture content.
5. Complete.
We implement this process by writing several functions.
The function make_dir() creates a directory. Determine whether the image file directory to be saved exists. If it does not exist, create the directory and set the directory to writable permissions.

Copy code The code is as follows:
function make_dir($path){
If(!file_exists($path)){//Create if it does not exist
​​​​ $mk=@mkdir($path,0777); //Permissions
​​​​​@chmod($path,0777);
}
Return true;
}

The function read_filetext() obtains the image content. Use fopen to open the image file, and then fread to read the image file content.
Copy code The code is as follows:

function read_filetext($filepath){
$filepath=trim($filepath);
$htmlfp=@fopen($filepath,"r");
//Remote
If(strstr($filepath,"://")){
​​​​while($data=@fread($htmlfp,500000)){
                 $string.=$data;
          }
}
//Local
else{
           $string=@fread($htmlfp,@filesize($filepath));
}
@fclose($htmlfp);
Return $string;
}

The function write_filetext() writes the file and writes the image content fputs into the file, that is, the image file is saved.
Copy code The code is as follows:

function write_filetext($filepath,$string){
//$string=stripSlashes($string);
$fp=@fopen($filepath,"w");
@fputs($fp,$string);
@fclose($fp);
}

The function get_filename() gets the image name, and you can also customize the file name to be saved.
Copy code The code is as follows:

function get_filename($filepath){
$fr=explode("/",$filepath);
$count=count($fr)-1;
Return $fr[$count];
}

Then combine several functions and call them in the function save_pic(), and finally return the saved picture path.
Copy code The code is as follows:

function save_pic($url,$savepath=''){
//Processing address
$url=trim($url);
$url=str_replace(" ","%20",$url);
//Read file
$string=read_filetext($url);
If(empty($string)){
echo 'Cannot read file';exit;
}
//File name
$filename = get_filename($url);
//Storage directory
Make_dir($savepath); //Create a storage directory
//File address
$filepath = $savepath.$filename;
//Write file
​ write_filetext($filepath,$string);
Return $filepath;
}

The last step is to call the save_pic() function to save the picture. We use the following code for testing.
Copy code The code is as follows:

//Target image address
$pic = "http://img0.pconline.com.cn/pconline/1205/06/2776119_end1_thumb.jpg";
//Save directory
$savepath = "images/";
echo save_pic($pic,$savepath);

In practical applications, we may collect the content of a certain site, such as product information, including collecting anti-hotlink pictures, and save them on the server on the website. At this time, we can use regular matching to match the page content, find all the matching pictures in the page, and then download them to the website server respectively to complete the collection of pictures. The following code is for testing only:
Copy code The code is as follows:

function get_pic($cont,$path){
$pattern_src = '//';
$num = preg_match_all($pattern_src, $cont, $match_src);
$pic_arr = $match_src[1]; //Get the picture array
foreach ($pic_arr as $pic_item) { //Loop to get the address of each picture
           save_pic($pic_item,$path); //Download and save the picture
echo "[OK]..!";
}
}

Then we analyze the page content, find out the main content, and call get_pic() to save the picture.
Copy code The code is as follows:

//We collect pictures from the content page of an article on PConline about mobile phones
$url = "http://gz.pconline.com.cn/321/3215791.html";

$content = file_get_contents($url);//Get web content
$preg = '#
(.*)
#iUs';
preg_match_all($preg, $content, $arr);
$cont = $arr[1][0];
get_pic($cont,'img/');

The above code has been personally tested by the author, and it can collect images, but there are still some scenarios that have not been taken into account. For example, the target website has made more than 302 jumps, and the target website has made various anti-collection methods. It is left to students who like to toss to try it. .

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/824692.htmlTechArticleWhen we need to collect the content of a web page on the Internet, if the pictures on the target website are protected from hotlinking , the pictures we collected directly are not available on our website. Then...
Statement
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
What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

How do you redirect a page in PHP?How do you redirect a page in PHP?Apr 28, 2025 pm 04:54 PM

The article discusses various methods for page redirection in PHP, focusing on the header() function and addressing common issues like "headers already sent" errors.

Explain type hinting in PHPExplain type hinting in PHPApr 28, 2025 pm 04:52 PM

Article discusses type hinting in PHP, a feature for specifying expected data types in functions. Main issue is improving code quality and readability through type enforcement.

What is PDO in PHP?What is PDO in PHP?Apr 28, 2025 pm 04:51 PM

The article discusses PHP Data Objects (PDO), an extension for database access in PHP. It highlights PDO's role in enhancing security through prepared statements and its benefits over MySQLi, including database abstraction and better error handling.

How to create API in PHP?How to create API in PHP?Apr 28, 2025 pm 04:50 PM

Article discusses creating and securing PHP APIs, detailing steps from endpoint definition to performance optimization using frameworks like Laravel and best security practices.

See all articles

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!