Home > Backend Development > PHP Tutorial > php利用curl实现多线程的类代码

php利用curl实现多线程的类代码

WBOY
Release: 2016-06-20 13:04:24
Original
1066 people have browsed it

php利用curl实现多线程的类代码

分享一个php多线程类(其实是php利用curl实现的一个多线程类),有了这个类,我们也可利用该类执行多线程任务了!

<?php<br />class curl_multi{<br /> private $url_list=array();<br /> private $curl_setopt=array(<br /> 'CURLOPT_RETURNTRANSFER' => 1,//结果返回给变量<br /> 'CURLOPT_HEADER' => 0,//是否需要返回HTTP头<br /> 'CURLOPT_NOBODY' => 0,//是否需要返回的内容<br /> 'CURLOPT_FOLLOWLOCATION' => 0,//自动跟踪<br /> 'CURLOPT_TIMEOUT' => 6//超时时间(s)<br /> );<br /> function __construct($seconds=30){<br /> set_time_limit($seconds);<br /> }<br /> /*<br /> * 设置网址<br /> * @list 数组<br /> */<br /> public function setUrlList($list=array()){<br /> $this->url_list=$list;<br /> }<br /> /*<br /> * 设置参数<br /> * @cutPot array<br /> */<br /> public function setOpt($cutPot){<br /> $this->curl_setopt=$cutPot+$this->curl_setopt;<br /> }<br /> /*<br /> * 执行<br /> * @return array<br /> */<br /> public function execute(){<br /> $mh=curl_multi_init();<br /> foreach($this->url_list as $i=>$url){<br /> $conn[$i]=curl_init($url);<br /> foreach($this->curl_setopt as $key => $val){<br /> curl_setopt($conn[$i],preg_replace('/(CURLOPT_w{1,})/ie','$0',$key),$val);<br /> }<br /> curl_multi_add_handle($mh,$conn[$i]);<br /> }<br /> $active=false;<br /> do{<br /> $mrc=curl_multi_exec($mh,$active);<br /> }while($mrc == CURLM_CALL_MULTI_PERFORM);<br /><br /> while($active and $mrc == CURLM_OK){<br /> if(curl_multi_select($mh) != -1){<br /> do{<br /> $mrc=curl_multi_exec($mh,$active);<br /> }while($mrc == CURLM_CALL_MULTI_PERFORM);<br /> }<br /> }<br /> $res=array();<br /> foreach($this->url_list as $i => $url){<br /> $res[$i]=curl_multi_getcontent($conn[$i]);<br /> curl_close($conn[$i]);<br /> curl_multi_remove_handle($mh,$conn[$i]);//释放资源 <br /> }<br /> curl_multi_close($mh);<br /> return $res;<br /> }<br />}
Copy after login

php使用多线程下载类示例:下载远程图片

$curl_mul=new curl_multi();<br />$curl_mul->setUrlList(array('http://www.baidu.com/img/baidu_sylogo1.gif','http://www.baidu.com/img/baidu_sylogo1.gif','http://www.baidu.com/img/baidu_sylogo1.gif'));<br />$a=$curl_mul->execute();<br />$i=1;<br />foreach($a as $v){<br />$filename=$i.'.gif';<br /> $fp2=@fopen($filename,'a');<br /> fwrite($fp2,$v);<br /> fclose($fp2);<br />$i++;<br />}
Copy after login


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template