PHP CURL并发,多线程

<?



/**
* php curl 并发 多线程
* @author suconghou <[email protected]>
* @version v1.0
* @blog http://blog.suconghou.cn
* @date 2013.12.25
* 
*/
class curl 
{
    private $mh;
    private $ch;
    
    function __construct()
    {
         $this-> mh=curl_multi_init();//创建批处理cURL句柄
    }



    //增加一个/组请求
    //url为array
    function add($url_array,$header=0,$no_body=0,$timeout=10)
    {
        is_array($url_array)||exit('should be a array');
        foreach ($url_array as  $value)
        {
            $this-> ch[$value]=curl_init();           
            curl_setopt_array($this-> ch[$value], array(CURLOPT_URL=>$value,CURLOPT_HEADER=>$header,CURLOPT_TIMEOUT=>$timeout,CURLOPT_NOBODY=>$no_body,CURLOPT_RETURNTRANSFER=>1));
            curl_multi_add_handle($this-> mh,$this-> ch[$value]);
        }
        return $this;

      
    }

    ///执行所有请求
    function exec()
    {
        $running=null;
        do
        {
            curl_multi_exec($this-> mh, $running);
            curl_multi_select($this-> mh);
        }
        while ($running > 0);
        foreach ($this-> ch as $key => $value)
        {
           $result[$key]=curl_multi_getcontent($value);
           curl_multi_remove_handle($this-> mh,$value);
           curl_close($value);
        }
        curl_multi_close($this-> mh);
        return $result;
    }

    //快速发起忽略返回值的并行请求
    function quick_exec($url_array)
    {

        is_array($url_array)||exit('should be a array');
        foreach ($url_array as $key => $value)
        {
            $this-> ch[$key]=curl_init();           
            curl_setopt_array($this-> ch[$key], array(CURLOPT_URL=>$value,CURLOPT_HEADER=>0,CURLOPT_TIMEOUT=>1,CURLOPT_NOBODY=>1));
            curl_multi_add_handle($this-> mh,$this-> ch[$key]);
        }
        $running=null;
        do
        {
            curl_multi_exec($this-> mh,$running);
        }
        while($running > 0);
        return true;

    }
}
///example

$t1=microtime(true);//计时开始


$curl=new curl();
$url=array('http://www.suconghou.cn','http://my.oschina.net/u/1163434/blog/186299','http://www.php.net/manual/zh/function.curl-multi-init.php','http://blog.csdn.net/tsxw24/article/details/7979172','http://www.360doc.com/content/12/1012/16/1440938_241070613.shtml');
$url2=array('http://www.baidu.com/s?tn=baiduhome_pg&ie=utf-8&bs=php+%E5%A4%9A%E7%BA%BF%E7%A8%8B&f=8&rsv_bp=1&rsv_spt=1&wd=php++curl%E5%A4%9A%E7%BA%BF%E7%A8%8B&rsv_sug3=4&rsv_sug=0&rsv_sug1=1&rsv_sug4=101&inputT=2336','http://blog.sina.com.cn/s/blog_63940ce20100neyb.html');
//$a=$curl->quick_exec($url);
$a=$curl->add($url,1,0)->add($url2)->exec();
$i=0;
foreach ($a as $key => $value)
{

    file_put_contents('1/'.$i.'.html',$value);
    $i++;
}

$t2=microtime(true); ///计时结束
echo $t2-$t1;



你可能感兴趣的:(PHP CURL并发,多线程)