search
HomeBackend DevelopmentPHP TutorialImplementation code for PHP multi-thread batch collection and downloading of pictures of beautiful women (continued)_PHP tutorial

Personally think the reason for the impact:
The matched image URL is not a valid URL. The article simply judges whether it is a relative path, but some URLs are invalid
The solution: add a new judgment to determine whether It is a picture of a real and valid URL

Copy code The code is as follows:

/**
*
* Determine whether the url is valid
*@param $url string
*@return boole
*/
function relUrl($url){
if(substr($url,0,4)=='http'){
$array = get_headers($url,true);
if(count($array)>0 && is_array ($array)){
if(preg_match('/200/', $array[0])){
unset($array);
return true;
}else{
unset($array);
return false;
}
}else{
unset($array);
return false;
}
}else{
return false;
}
}

Mainly use the get_headers function to obtain http request information, determine the server response status (200) and determine whether the url is real and valid.

Test collecting pictures again
The results are worse than before and the operation is even slower.

The reason for the test is:
Although the get_headers function can determine whether the URL is real and valid, if it encounters a very slow URL resource, because there is no time limit for the get-heades request, this thread will be occupied and subsequent requests will be blocked. Blocking
file_get_content function has the same reason as above. Since some slow URL resources are occupied for a long time, the process behind the blocking is occupied. If blocked for a long time, the CPU usage will also increase
Solution;
Use curl Multi-threading. In addition, curl can set the request time. When encountering a very slow URL resource, you can give up decisively, so there is no blocking. In addition, multi-threaded requests should be more efficient. Reference: "The Learning and Application of CURL [Attached to Multi-Threading" ]》, let’s test it again;

Core code:

Copy code The code is as follows:

/**
     * curl 多线程
     * 
     * @param array $array 并行网址
     * @param int $timeout 超时时间
     * @return mix
     */
 public function Curl_http($array,$timeout='15'){
      $res = array();

      $mh = curl_multi_init();//创建多个curl语柄

      foreach($array as $k=>$url){
          $conn[$k]=curl_init($url);//初始化

          curl_setopt($conn[$k], CURLOPT_TIMEOUT, $timeout);//设置超时时间
          curl_setopt($conn[$k], CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
          curl_setopt($conn[$k], CURLOPT_MAXREDIRS, 7);//HTTp定向级别 ,7最高
          curl_setopt($conn[$k], CURLOPT_HEADER, false);//这里不要header,加块效率
          curl_setopt($conn[$k], CURLOPT_FOLLOWLOCATION, 1); // 302 redirect
          curl_setopt($conn[$k], CURLOPT_RETURNTRANSFER,1);//要求结果为字符串且输出到屏幕上         
    curl_setopt($conn[$k], CURLOPT_HTTPGET, true);

          curl_multi_add_handle ($mh,$conn[$k]);
      }
       //防止死循环耗死cpu 这段是根据网上的写法
          do {
              $mrc = curl_multi_exec($mh,$active);//当无数据,active=true
          } while ($mrc == CURLM_CALL_MULTI_PERFORM);//当正在接受数据时
          while ($active and $mrc == CURLM_OK) {//当无数据时或请求暂停时,active=true
              if (curl_multi_select($mh) != -1) {
                  do {
                      $mrc = curl_multi_exec($mh, $active);
                  } while ($mrc == CURLM_CALL_MULTI_PERFORM);
              }
          }

      foreach ($array as $k => $url) {
            if(!curl_errno($conn[$k])){
             $data[$k]=curl_multi_getcontent($conn[$k]);//数据转换为array
             $header[$k]=curl_getinfo($conn[$k]);//返回http头信息
             curl_close($conn[$k]);//关闭语柄
             curl_multi_remove_handle($mh  , $conn[$k]);   //释放资源
            }else{
             unset($k,$url);
            }
          }

          curl_multi_close($mh);

          return $data;

   }

//参数接收
$callback = $_GET['callback'];
$hrefs = $_GET['hrefs'];
$urlarray = explode(',',trim($hrefs,','));
$date = date('Ymd',time());
//实例化
$img = new HttpImg();
$stime = $img->getMicrotime();//开始时间

$data = $img->Curl_http($urlarray,'20');//List data
mkdir('./img/'.$date,0777);
foreach ((array )$data as $k=>$v){
preg_match_all("/(href|src)=(["|']?)([^ "'>]+.(jpg|png|PNG |JPG|gif))2/i", $v, $matches[$k]);

if(count($matches[$k][3])>0){
$dataimg = $img->Curl_http($matches[$k][3],'20');//All image data binary
$j = 0;
foreach ((array)$dataimg as $kk=>$vv){
if($vv !=''){
$rand = rand(1000,9999);
$basename = time()."_".$ rand.".".jpg;//Save the file in jpg format
$fname = './img/'.$date."/"."$basename";
file_put_contents($fname, $ vv);
$j++;
echo "Create the ".$j." picture"."$fname"."
";
}else{
unset ($kk,$vv);
}
}
}else{
unset($matches);
}
}
$etime = $img-> getMicrotime();//End time
echo "time".($etime-$stime)."seconds";
exit;

Test the effect
Implementation code for PHP multi-thread batch collection and downloading of pictures of beautiful women (continued)_PHP tutorial
It takes about 260 seconds to collect 337 pictures. Basically, it can collect one picture in one second. It is also found that the more pictures there are, the more obvious the collection speed is.

We can take a look at the file naming: that is, we can generate 10 pictures at the same time,

Due to the 20-second request time limit, some pictures are obviously incomplete after being generated, that is, the picture resources are not fully collected within 20 seconds. You can set this time yourself.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327372.htmlTechArticlePersonally I think the reason for the impact: The matched image URL is not a valid URL. The article just simply judges whether it is. Relative path, but some URLs are invalid. The solution is to add...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

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: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

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 and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

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 and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

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.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

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 and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

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.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

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

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

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.

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 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)