We introduced in the previous article, PHP Multi-threaded class implementation method, today this article to introduce you how to use curl to implement multithreading method, with this class, we can also use this class to perform multi-threaded tasks!
PHP uses curl to implement a multithreaded class example
<?php class curl_multi{private $url _list=array (); Private $curl _setopt=array (' curlopt_returntransfer ' = = 1,//results returned to the variable ' curlopt_header ' = 0,//need to return HT TP Head ' curlopt_nobody ' = = 0,//need to return the content ' curlopt_followlocation ' + 0,//auto tracking ' curlopt_timeout ' = = 6//Time-out (s)); function construct ($seconds =30) {set_time_limit ($seconds); }/* * Set URL * @list Array */Public function seturllist ($list =array ()) {$this->url_list= $li St }/* * Set parameters * @cutPot Array */Public function setopt ($cutPot) {$this->curl_setopt= $cutP ot+ $this->curl_setopt; }/* * Execute * @return Array */Public function execute () {$MH =curl_multi_init (); foreach ($this->url_list as $i = + $url) {$conn [$i]=curl_init ($url); foreach ($this->curl_setopt as $key = + $val) {curl_setopt ($conn [$i],preg_replaCE ('/(Curlopt_\w{1,})/ie ', ' $ A ', $key), $val); } curl_multi_add_handle ($MH, $conn [$i]); } $active =false; do{$MRC =curl_multi_exec ($MH, $active); }while ($MRC = = Curlm_call_multi_perform); while ($active and $MRC = = CURLM_OK) {if (Curl_multi_select ($MH)! =-1) {do{ $MRC =curl_multi_exec ($MH, $active); }while ($MRC = = Curlm_call_multi_perform); }} $res =array (); foreach ($this->url_list as $i = + $url) {$res [$i]=curl_multi_getcontent ($conn [$i]); Curl_close ($conn [$i]); Curl_multi_remove_handle ($MH, $conn [$i]);//Release Resources} curl_multi_close ($MH); return $res; } }
PHP uses multi-threaded Download class example: Download remote picture
$curl _mul=new Curl_multi (); $curl _mul->seturllist (Array (' http://www.baidu.com/img/baidu_sylogo1.gif ')); $a = $curl _mul->execute (); $i = 1; foreach ($a as $v) { $filename = $i. '. gif '; $FP 2= @fopen ($filename, ' a '); Fwrite ($fp 2, $v); Fclose ($fp 2); $i + +; }
Summarize:
This article introduces you to PHP using Curl implementation of multi-threaded class instances, as well as PHP curl multi-Threaded download image instances, I hope that the work can help!
Related recommendations:
Implementing a PHP Multithreaded class case
PHP Implementation method of asynchronous call multithreading
Introduction to three ways of implementing PHP multithreaded simulation
php implementation instance of multi-threading