Use PHP to collect remote pictures_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 function of collecting remote pictures. 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. Completed. 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. function make_dir($path){ if(!file_exists($path)){//If it does not exist, create it $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. 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 a file and writes the image content fputs into the file, that is, saving the image file. 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. 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. 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. //Target image address $pic = "/program/UploadPic/2013-4/201343155341353.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-leeching pictures, and save them to 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: 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. //We collected pictures of 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);//获取网页内容 $preg = '#<div>(.*)<div></div>#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. . <p align="left"></p> <div style="display:none;"> <span id="url" itemprop="url">http://www.bkjia.com/PHPjc/371938.html</span><span id="indexUrl" itemprop="indexUrl">www.bkjia.com</span><span id="isOriginal" itemprop="isOriginal">true</span><span id="isBasedOnUrl" itemprop="isBasedOnUrl">http: //www.bkjia.com/PHPjc/371938.html</span><span id="genre" itemprop="genre">TechArticle</span><span id="description" itemprop="description">When 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...</span> </div> </div> <div class="art_confoot"></div>

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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.

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.